Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton Backbone models with RequireJS: anti-pattern?

I have a model that needs to be accessed by several views and to accomplish this in the definition of the model module I'm instantiating it immediately like so:

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

    return new Foo();
});

I only really need one instance of this model - right now that is. 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 instantiate and store references to objects on app startup:

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

but I feel like this is a poor alternative since you're essentially going back to having a global namespace - which is something that RequireJS is supposed to help avoid.

Are there any alternatives and is there any good reason to avoid having singleton models as I described above?

like image 616
Radu Avatar asked Sep 21 '12 03:09

Radu


2 Answers

Hmm.. I have been using the RequireJS modules as Singleton objects for a while with no problem. Here is a related question that I asked.

Is it a bad practice to use the requireJS module as a singleton?

Hope this helps!

like image 51
Karthik Avatar answered Nov 15 '22 17:11

Karthik


You don't need to create the namespace thing. Your first example creates a singleton. Whenever you require this module you get the same instance of your model. So instead of creating a new App module and save the instance there, just require the module of your first example directly. We use it in our app to have a singleton instance of our app and I can see no pitfalls with this.

like image 38
Andreas Köberle Avatar answered Nov 15 '22 15:11

Andreas Köberle