Singleton Backbone Models with RequireJS: Anti-Pattern?

I have a model that needs to be accessed through several views, and for this, in the definition of the model module, I create it right away:

define([ 'jquery', 'underscore', 'backbone' ], function(_, Backbone) { var Foo = Backbone.Model.extend({ // wondrous methods and properties }); return new Foo(); }); 

I really only need one instance of this model - right now. The workaround for this, as far as I know, is to have a separate App module. Something like:

 define([], function() { var App = { routers: {}, models: {}, views: {} }; return App; }); 

on which you can create and store links to objects when the application starts:

 require([ 'App', 'Foo' ], function(App, Foo) { App.models.foo = new Foo(); }); 

but I feel this is a bad alternative, since you are essentially reverting to the global namespace - this is what RequireJS should avoid.

Are there any alternatives and are there good reasons to avoid using singleton models as described above?

+8
javascript requirejs
source share
2 answers

Hmm .. I used RequireJS modules as Singleton objects, but no problem. Here is the related question that I asked.

Is it wrong to use requireJS module as single?

Hope this helps!

+5
source share

You do not need to create a namespace object. The first example creates a singleton. Whenever you need this module, you get the same instance of your model. Therefore, instead of creating a new App module and saving the instance there, the module of your first example is simply required. We use it in our application to have one instance of our application, and I do not see any problems with this.

+3
source share

All Articles