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?
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!
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.
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