1

I read the following on the web this weekend and I wanted to know if most others consider this the right (better) way of doing things.

This is not the best (right) way to do things:

$(document).ready(function() {
    $('#magic').click(function(e) {
        $('#yayeffects').slideUp(function() {
            // ...
        });
    });

    $('#happiness').load(url + ' #unicorns', function() {
        // ...
    });
});

That this is better:

var PI = {
    onReady : function() {
        $('#magic').click(PI.candyMtn);
        $('#happiness').load(PI.url + ' #unicorns', PI.unicornCb);
    },
    candyMtn : function(e) {
        $('#yayeffects').slideUp(PI.slideCb);
    },
    slideCb : function() { ... },
    unicornCb : function() { ... }
};

$(document).ready(PI.onReady);

Does one perform better than the next? Easier for debugging?

Thoughts? Comments?

2
  • 3
    Couple of things: (1) This is phrased in a way to say "B is better than A. What do you think?" which loads the question. (2) You don't state why you feel that the second is better, despite saying that it is. Commented Feb 7, 2011 at 13:39
  • Just an FYI but in later versions of jQuery $(function(){...}) is equivalent to $(document).ready(function(){...}) Commented Feb 7, 2011 at 14:06

2 Answers 2

1

If you have a stacktrace with lots of anonymous functions in it it takes significantly more time to find out where the error exactly has happened and from where it was called. so plus 1 for second.

The code inside an event handler has often not much to do with the code where the handler gets registered and should therefore be in a separate function/module. plus 1 for second.

Using anonymous functions for listeners is also bad because in case you have to remove this listeners (which most people don't care about) you can remove only them and you don't have to care about accidentally removing other listeners form other parts of code. plus 1 for the second.

Put the related functions into a single object is not necessarily the best. Mostly the onReady function is bad if you use the behaviour of the listeners for different dom objects.

don't care about performance. a listener is usually not called that often that it matters.If it does, there is most likely a problem somewhere else.

Sign up to request clarification or add additional context in comments.

Comments

0

The second variant is reusable - you can reuse slideCb and other handlers for other events for other controls.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.