Best Practices: Avoid Anonymous Functions

Anonymous functions are often used when binding event handlers.
However, anonymous functions are difficult to debug, maintain, test, or reuse.

It’s better to use object literals:

//BAD
$(document).ready(function() {
  $('.status .delete').click(function(e) {
    //Do something
  });

  $('.status').dblclick(function(e) {
    //Do the same thing
  });
});

//GOOD
var bindingObject = {
  onReady : function() {
    $('.status .delete').click(bindingObject.deleteTweet);
    $('.status').dblclick(bindingObject.deleteTweet);
  },
  deleteTweet : function(e) {
    //Do something
  }
};

$(document).ready(bindingObject.onReady);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s