I have a fairly generic model and collection of that model (see below) I am dealing with as the basis for a series of views. On several of the views, the selection of one of the models generates actions (via the 'selected' attribute), and I need to be able to keep track of the selection on just the client side.
However, it appears that there is no clean way to do this in Backbone. Any attributes added to/changed on the model on the client will be sync'd up to the server. I can't use {silent : yes}
when changing that attribute because I need to trigger changes in my views when the change
event fires on that attribute. The only way I have come up with to do this is to overwrite the save
function on Backbone.Model
My question: is there a way to have client-side only attributes that I am missing OR is my approach structurally flawed in some other way that I am just not seeing?
var CSEvent = Backbone.Model.extend({
idAttribute: "_id",
urlRoot : '/api/events',
defaults: {
title : "",
type : "Native",
repeatOrOneTime : "OneTime",
selected : false
}
});
var CSEventCollection = Backbone.Collection.extend({
model: CSEvent,
url: '/api/events',
getSelectedEvent : function() {
return this.find(function(csevent) { return csevent.get('selected') === true; });
},
selectEvent : function(eventId) {
this.deselectEvent();
this.get(eventId).set({selected : true});
},
deselectEvent : function() {
this.getSelectedEvent().set({selected : false});
}
});
Try to override the Model.toJSON()
method, as you can see in the Backbone Model code this method is not very complicate. Also the official documentation suggests to override it in case of special needs.
Try something like this:
var CSEvent = Backbone.Model.extend({
toJSON: function(){
return _.clone( _.pick( this.attributes, "title", "type", "repeatOrOneTime" ) );
}
});
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