Rethna
Rethna

Reputation: 231

RequireJS / BackboneJS app - Need suggestion on adding dependency

I am developing an app using backboneJS/requireJS. I have identified around 20 views, and for all the views I am using jquery, backbonejs and underscorejs. So my first three dependencies are always these three.

define([
  'jquery', 
  'underscore', 
  'backbone',
 .... ], function($, _, Backbone, ..){
.....

});

Is there a way i can skip and say somewhere at global level to include these three in all modules, so that I can avoid writing them redundantly in all files?

Upvotes: 0

Views: 51

Answers (1)

glortho
glortho

Reputation: 13200

There are a few ways to do this. One is to wrap define in your own myDefine (or whatever):

myDefine = function(dependencies, callback) {
  var defaults = ['jquery', 'underscore', 'backbone'],
      combined = defaults.concat(dependencies);

  return define(combined, callback);
};

myDefine(['MyView'], function($, _, Backbone, MyView) {
  // do stuff
});

But this obviously still requires you to specify the objects in your callback. So a better option might be to attach $, _, and Backbone to your application namespace (if you don't want them to be global). Then you could do something like this:

myDefine = function(dependencies, callback) {
  var defaults = ['jquery', 'underscore', 'backbone'];

  if (myApp.$ && myApp._ && myApp.Backbone) {
    define(dependencies, callback);
  } else {
    require(defaults, function($, _, Backbone) {
      myApp.$ = $;
      myApp._ = _;
      myApp.Backbone = Backbone;
      define(dependencies, callback);
    }
  }
};

myDefine(['MyView'], function(MyView) {
  // use myApp.$, myApp._, myApp.Backbone
});

If you don't care about namespacing, you could just do the above without the myApp steps and let the libs stay in window.

Note that all above is untested.

The simpler option of course is simply to load jQuery, Underscore, and Backbone synchronously before any of your modules.

Upvotes: 1

Related Questions