Lazycoder

4Aug/095

jQuery tip – beware anonymous functions in your event handlers

jQuery makes it really easy to wire up event handlers using anonymous functions.

CODE:
  1. <script type="text/javascript">
  2.     $(document).ready(function()
  3.     {
  4.         $("#Button1").click(function(event)
  5.         {
  6.             alert("You Clicked Me!");
  7.         });
  8.     });
  9. </script>

In this case you are just wiring up one element to an event. Lets consider the case where you have a larger number of elements on the page and want to hook up to a click event on each one.

CODE:
  1. $(document).ready(function(){
  2.             for(var i =0;i<10000;i++)
  3.             {
  4.                 $("#bigContainer").append("<input type='button' class='clickybutton' id='button" + i + "' value='button" + i + "'> ");
  5.             };
  6.            
  7.             $(".clickybutton").click(function(e){
  8.                 alert(e.target.id);
  9.             });
  10.         });

In this case, a new anonymous function will be created for each element on the page. This can waste a lot of memory. It's sometimes better to use event delegation. That is, to let the event bubble up to a single containing element which then determines a course of action for the element that was clicked.

CODE:
  1. $(document).ready(function(){
  2.             for(var i =0;i<10000;i++)
  3.             {
  4.                 $("#bigContainer").append("<input type='button' class='clickybutton' id='button" + i + "' value='button" + i + "'> ");
  5.             };
  6.             $("#bigContainer").click(function(e){
  7.                 if($(e.target).hasClass("clickybutton"))
  8.                     alert(e.target.id);
  9.             });
  10.         });

If you want to learn more about JavaScript, I'd recommend reading the following books:

  • http://encosia.com Dave Ward

    I believe that’s how live() is implemented, so you could also use its slightly more concise syntax to accomplish the same thing.

  • http://www.lazycoder.com Scott

    Dave:

    Yes, you’re correct. The live function does bind it’s events to the document and delegate up. In jQuery 1.3.3, I believe, you’ll be able to specify a context for the live() event just like any other selector so they will be a little faster (in large DOMs).

  • Pingback: Dew Drop – August 5, 2009 | Alvin Ashcraft's Morning Dew

  • http://www.thinkbluemedia.co.uk Robert Rawlins

    Excellent little tip, I’m fairly new to jQuery development and things like this I don’t even really consider, so long as my code is working I’m happy. This has changed my thinking quite considerably.

    Thanks,

    Rob

  • http://www.looseideas.co.uk Ryan Mitchell

    Obvious but maybe worth pointing out for those just starting out. You don’t need to use an anonymous function here, use a named function and the event will be passed through as the argument. I think you’d still get the memory hit of the binding but not of the function.

  • scary

    CRIMES AGAINST POSTERITY
    SWINE FLU SWINDLE
    SWINES FLEW IN TOP HATS
    Glaxo is just a marketing hand
    so who sold that vacc to the whole world carrying seeds of the next pandemic?
    What state, what monster?
    When failed, getting away to try again?
    Like Oklahoma
    your comment must be approved by
    OH YEAH?
    guess where all the internet monitoring flows to and you guessed where that vaccine maker sits
    According to a list compiled by Dr. Patricia Doyle at rense.com, a host of strange ingredients are used to make up Hoffman-La Roche’s anti-flu drug Tamiflu, which has recently been connected with bizarre behavior,
    Patients using Tamiflu — which many nations are stocking up on as a way to combat a possible pandemic of the deadly H5N1 bird flu — reported delirium, hallucinations, delusions, convulsions, disturbed consciousness and abnormal behavior. The FDA reports that side effects reported with Tamiflu include nausea, vomiting, diarrhea, bronchitis, stomach pain, dizziness and headache.
    ANTI-MONOPOLISTS VERY QUIET ON JUST ONE FIRM ”SERVING” THE WHOLE WORLD
    COMING SOON FROM THE SAME CREEPS: CARBON SIN RELIC INDULGENCES, PAYABLE GUESS TO WHOM.
    Hint 1, it never was the Pope.
    Hint 2, when exposed with biggest fake relics collection ever, the perpetrators protest laudest and become The Reformation Crowd.
    Hint 3, See Barnum’s Humbugs of all times 1860 book, chapter on Moon Hoax

  • Pingback: event handlers - StartTags.com