public
Last active

$(function(){...}) vs (function($){...})($)

  • Download Gist
1.js
JavaScript
1 2 3
(function($) {
// Backbone code in here
})(jQuery);
2.js
JavaScript
1 2 3
$(function(){
// Backbone code in here
});
3.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
// 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();
});

I've often used the pattern:

jQuery(function($) {
  // Safely use $ here
});

nice - didn't know jQuery passed itself in as a reference like that.

I usually do this which might be an overkill.

(function($){
    $(function(){
         // code here...
    });
})(jQuery);

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.