Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why define an anonymous function and pass it jQuery as the argument?

I'm looking through the excellent peepcode demo code from the backbone.js screencasts. In it, the backbone code is all enclosed in an anonymous function that is passed the jQuery object:

(function($) {   // Backbone code in here })(jQuery); 

In my own backbone code, I've just wrapped all my code in the jQuery DOM 'ready' event:

$(function(){   // Backbone code in here }); 

What's the point/advantage of the first approach? Doing it this way creates an anonymous function that is then executed immediately with the jQuery object being passed as the function argument, effectively ensuring that $ is the jQuery object. Is this the only point - to guarantee that jQuery is bound to '$' or are there other reasons to do this?

like image 604
Matt Roberts Avatar asked Apr 29 '12 10:04

Matt Roberts


People also ask

Why would you use an anonymous function?

The advantage of an anonymous function is that it does not have to be stored in a separate file. This can greatly simplify programs, as often calculations are very simple and the use of anonymous functions reduces the number of code files necessary for a program.

Is it valid to pass an anonymous function as an argument to another function?

They're called anonymous functions because they aren't given a name in the same way as normal functions. Because functions are first-class objects, we can pass a function as an argument in another function and later execute that passed-in function or even return it to be executed later.

Why are anonymous functions useful in JavaScript?

Summary. Anonymous functions are functions without names. Anonymous functions can be used as an argument to other functions or as an immediately invoked function execution.

Why are anonymous functions frequently used with event handlers?

More generally, the point of using anonymous functions is that they do not require a name, because they are "event handlers" bound to a specific event on a specific object. In this case, the object is the entire Document Object Model, and the anonymous function executes when the entire DOM has loaded.


1 Answers

The two blocks of code you have shown are dramatically different in when and why they execute. They are not exclusive of each other. They do not serve the same purpose.

JavaScript Modules

 (function($) {   // Backbone code in here })(jQuery); 

This is a "JavaScript Module" pattern, implemented with an immediately invoking function.

  • http://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript
  • http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

The purpose of this code is to provide "modularity", privacy and encapsulation for your code.

The implementation of this is a function that is immediately invoked by the calling (jQuery) parenthesis. The purpose of passing jQuery in to the parenthesis is to provide local scoping to the global variable. This helps reduce the amount of overhead of looking up the $ variable, and allows better compression / optimization for minifiers in some cases.

Immediately invoking functions are executed, well, immediately. As soon as the function definition is complete, the function is executed.

jQuery's "DOMReady" function

This is an alias to jQuery's "DOMReady" function: http://api.jquery.com/ready/

 $(function(){   // Backbone code in here }); 

jQuery's "DOMReady" function executes when the DOM is ready to be manipulated by your JavaScript code.

Modules vs DOMReady In Backbone Code

It's bad form to define your Backbone code inside of jQuery's DOMReady function, and potentially damaging to your application performance. This function does not get called until the DOM has loaded and is ready to be manipulated. That means you're waiting until the browser has parsed the DOM at least once before you are defining your objects.

It's a better idea to define your Backbone objects outside of a DOMReady function. I, among many others, prefer to do this inside of a JavaScript Module pattern so that I can provide encapsulation and privacy for my code. I tend to use the "Revealing Module" pattern (see the first link above) to provide access to the bits that I need outside of my module.

By defining your objects outside of the DOMReady function, and providing some way to reference them, you are allowing the browser to get a head start on processing your JavaScript, potentially speeding up the user experience. It also makes the code more flexible as you can move things around without having to worry about creating more DOMREady functions when you do move things.

You're likely going to use a DOMReady function, still, even if you define your Backbone objects somewhere else. The reason is that many Backbone apps need to manipulate the DOM in some manner. To do this, you need to wait until the DOM is ready, therefore you need to use the DOMReady function to start your application after it has been defined.

You can find plenty of examples of this around the web, but here's a very basic implementation, using both a Module and the DOMReady function:

  // Define "MyApp" as a revealing module  MyApp = (function(Backbone, $){    var View = Backbone.View.extend({     // do stuff here     });    return {     init: function(){       var view = new View();       $("#some-div").html(view.render().el);     }   };  })(Backbone, jQuery);    // Run "MyApp" in DOMReady  $(function(){   MyApp.init(); }); 
like image 116
Derick Bailey Avatar answered Sep 24 '22 22:09

Derick Bailey