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?
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:
this.$
to access the local DOM, this.$el
for the elementBackbone.$
stores a reference to jQueryIt'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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With