I am starting developing an application with backbone+require. I want to share a same instance of a Model between several views. I have defined the model as a singleton, and thus all the views access the same instance of the model.
I have evaluated two options:
1.Use Events with the instance of the Model as a parameter to communicate views
2.Share the same instance of the model between views.
I have chosen the second option, adding a new line to my Model:
define(['Underscore','Backbone'],
function(_, Backbone) {
var Experience = Backbone.Model.extend({
defaults: {
'id' : 1,
'date' : '2012-10-11 '
}
});
if (this.model === undefined) return new Experience();
});
And then I bind the model to my views
define([ 'jQuery','Underscore','Backbone','models/experience'
], function($, _, Backbone, Experience){
var MyView1 = Backbone.View.extend({
initialize: function () {
this.model = Experience;
....
This way, all the views with this model share it.
Is there a better way for sharing instances of a model in backbone? Would it be better to use events and the instances as parameters?
IMHO a Singleton is the way to go in your case.
Passing instances to views would be useful in case of a very generic view that is shared between a lot o models and as far as I can see it’s not your case.