Is there a standard way to deal with non-saveable values in Backbone.
e.g.
MyModel = Backbone.extend(Backbone.Model, {
initialize: function () {
this.set({'inches': this.get('mm') / 25});
}
})
If I call save() on this model it will throw an error as there is no corresponding database field for inches. I can think of a few ways to fix this, but am wondering if there’s a tried and tested approach generally best used for this?
At the moment my preferred solution is to extend Backbone’s toJSON method and to allow passing of a boolean parameter dontCleanup to allow for it to still return all the model’s values (including the non saveable ones) when it’s needed e.g. for passing to a template.
I like Peter Lyon’s idea. I’ve thought about that a few times, but never actually put it in place. For all the ways that I have handled this, though, here are my two favorites:
Non-Attribute Values
This one is simple: don’t store the values you need in the model’s standard attributes. Instead, attach it directly to the object:
The big problem here is that you don’t get all of the events associated with calling
seton the model. So I tend to wrap this up in a method that does everything for me. For example, a common method I put on models isselectto say that this model has been selected:In your case, I’m not sure this would be a good approach. You have data that needs to be calculated based on the values that are in your attributes already.
For that, I tend to use view models.
View models.
The basic idea is that you create a backbone model that is persist-able, as you normally would. But the you come along and create another model that inherits from your original one and adds all the data that you need.
There are a very large number of ways that you can do this. Here’s what might be a very simple version:
The big benefit of wrapping this with
Object.createis that you now have a prototypal inheritance situation, so all of your standard functionality from the model is still in place. We’ve just overridden thetoJSONmethod on the view model, so that it returns the JSON object with theinchesattribute.Then in a view that needs this, you would wrap your model in the initialize function:
render: function(){
var data = this.model.toJSON(); // returns with
inches}
});
You could call
new MyViewModel(this.model)if you want, but that's not going to do anything different, in the end, because we're explicitly returning an object instance from theMyViewModelfunction.When your view's render method calls
toJSON, you'll get theinchesattribute with it.Of course, there are some potential memory concerns and performance concerns with this implementation, but those can be solved easily with some better code for the view model. This quick and dirty example should get you down the path, though.