Reputation: 5968
I have a model in which I am using in multiple views. I want to detect a change event on that model (save it to localStorage for persistent) but I want the change to be independent of each view.
Is there a way to bind a model change event on the model itself, or in the controller (I'm also using Marionette and Require)? Here is my model:
define([
'backbone',
'common'
],
function(Backbone, Common) {
//Define the App Namespace before anything else
var APP = Common.app_namespace || {};
APP.Models.UserModel = Backbone.Model.extend({
//Set up default values
defaults: {
"value" : "default"
}
});
});
Is there an easy way to do this? I was thinking of using backbone.localStorage but (please please please correct me if I'm wrong) I think that the model in question needs to be in a collection, but since I don't need a collection, I was hoping to do this manually.
Upvotes: 0
Views: 1354
Reputation: 8293
Backbone.Model extends Backbone.Events, so yes, it can listen and trigger events:
APP.Models.UserModel = Backbone.Model.extend({
//Set up default values
defaults: {
"value" : "default"
},
initialize: function() {
this.listenTo(this, 'change', this.myCallback);
}
});
Upvotes: 2