Question

I have a Backbone application which uses require.js and I'm trying to work out if the resources defined lower down the chain are inherited up through the prototype chain which does appears to be the case. If this is correct what is the best practice, should I define them again or not?

My example, I have a base model which provides some custom behaviour which will be common across all my models.

// Base Model
define([
    'backbone'
],
function (Backbone) {
    'use strict';

    return Backbone.Model.extend({

        fetch: function (options) {
            options = options ? options : {};
            options.data = options.data ? options.data : {};
            options.data.nocache = $.now();
            return Backbone.Model.prototype.fetch.call(this, options);
        }
    });
});

Then I have other models which extend the base model to inherit these common functions.

// Some other model
define([
    'app',
    'backbone',
    'models/base/model'
], 
function(App, Backbone, BaseModel) {
    'use strict';

    return BaseModel.extend({

        url : function() {
            return 'some/url/;
        }   
    });
});

As you can see I've defined backbone as a resource in both models but since the other models inherit from the base model. Do I really need to define backbone here?

I'm looking for best practice, thanks!

Was it helpful?

Solution

I always define everything required for a module to run. If you don't, it's not really portable. If you, in the future, remove an upstream dependency, your downstream model can also break. ie,

define('a', ['app','backbone','myplugin', ...]
define('b', ['app','backbone','a', ...]

If b and a both use myplugin, then at some point in the future a no longer needs it, when you remove myplugin from a you will break b without knowing it.

OTHER TIPS

In case if you have a bunch of some-other-models, I would recommend putting them to shim of your require.js config file like that:

require.config({
  paths: {
    'backbone': 'path/to/backbone'
  },

  shim: {
    'models/*': { deps: [ 'backbone' ] }
  }
});

And then you will be able to declare deps for your some-other-model knowing that backbone is there already:

define(['app', 'models/base/model'], function (App, BaseModel) {
  // backbone is already loaded here
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top