6
votes

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?

2
what if you want to use a module you've defined in another project?kinakuta
You answered 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 are cruft.nikoshr

2 Answers

3
votes

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:

1
votes

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 :)