A few options:
You could create a generic backbone model and use it to store & listen to properties of the view state.
StatefulView = Backbone.View.extend({
initialize: function(options) {
this.state = new Backbone.Model({
selected: !!options.selected
});
this.listenTo(this.state, 'change:selected', this.renderSelectedState);
},
// ...
});
I would recommend against storing any kind of view-related property in your model, because as your app grows, it is not a scalable solution if you display the same model in multiple selectable lists, for example. But... You could override your model's toJSON
function to remove attributes you don't want to persist:
ModelWithClientAttributes = Backbone.Model.extend({
toJSON: function(withClientAttrs) {
var json = Backbone.Model.prototype.toJSON.call(this);
if (withClientAttrs) return json;
return _(json).omit(this.clientAttrs);
},
// ...
});
// Extend from that base class when defining your model, and define the 'clientAttrs' property
Post = ModelWithClientAttributes.extend({
clientAttrs: ['selected', 'checked'],
// ...
});
// Then, in your view:
render: function() {
this.$el.html(
this.template(
this.model.toJSON( true )
)
);
}
// Backbone.sync will call toJSON without arguments, so they will receive the filtered json representation
var post = new Post({
selected: true,
title: 'May Snow Storm',
body: '...'
});
post.save();
console.log(post.toJSON()); // {"title": "May Snow Storm", "body": "..."}
console.log(post.toJSON(true)); // {"selected": true, "title": "May Snow Storm", "body": "..."}
Probably the safest and best solution is to simply whitelist the attributes that you want to persist in your server-side code.