Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why include jQuery and underscore in every JS file in Backbone/Require.js project

In almost every Backbone/Require.js project you will see models and views that look similar to this:

define([
    'jquery',
    'underscore',
    'backbone'
], function ($, _, Backbone) {
    //Some code goes here, perhaps a Backbone model or view
});

But, assuming that you set up your Require.js shims correctly (with the Backbone shim including something like deps: ["underscore", "jquery"]) you only need to define Backbone--defining Backbone as a dependency implicitly defines jQuery and Underscore as dependencies as well! Thus this would also be correct:

define([
    'backbone'
], function (Backbone) {
    //Some code goes here, perhaps a Backbone model or view
});

Personally, I would define jQuery or Underscore in a file that explicitly used their functions--but in something like a simple no-frills Backbone model file, they seem like cruft.

Why do I so frequently see the pattern of superfluous jQuery and Underscore definitions? Why has this become an unquestioned best practice?

like image 345
Lochlan Avatar asked Jan 08 '14 05:01

Lochlan


2 Answers

Declaring Underscore and jQuery as dependencies when you don't explicitly need them as variables in your module doesn't serve any purpose (i.e. it is not a best practice). As you said in your question

Personally, I would define jQuery or Underscore in a file that explicitly used their functions--but in something like a simple no-frills Backbone model file, they seem like cruft.

Moreover, you can even get rid of them in some situations:

  • in views, use this.$ to access the local DOM, this.$el for the element
  • Backbone.$ stores a reference to jQuery
  • use the proxied methods of Underscore on models and collections
like image 53
nikoshr Avatar answered Oct 12 '22 22:10

nikoshr


It's done only because of avoiding using global variables. Of course you can skip defining jQuery and underscore but $ and _ will refer to the global variables in this case. In case you create your own application and use single version of jQuery - it will not case issues, but if your application already includes few different library versions - it's better to follow practice you do not like to follow :)

like image 33
Vitalii Petrychuk Avatar answered Oct 12 '22 22:10

Vitalii Petrychuk