I would like to access the calculated fields I have implemented in the model (backbone.js) from the template. Do I need always to define a helper to do it?
I think the problem has to do with the way I pass the model to the template. If I pass this.model.toJSON() I have access to the properties but not to the functions I have defined in it. If I pass this.model directly I can access the function but not the properties of the backbone model.
Always pass this.model.toJSON()
to your templates.
What you need to do to get your calculated values, is override your toJSON
method on your model.
MyModel = Backbone.Model.extend({
myValue: function(){
return "this is a calculated value";
},
toJSON: function(){
// get the standard json for the object
var json = Backbone.Model.prototype.toJSON.apply(this, arguments);
// get the calculated value
json.myValue = this.myValue();
// send it all back
return json;
}
})
And now you have access to myValue
from the the JSON that is returned by toJSON
, which means you have access to it in the view.
The other option, as you mentioned, is to build helper methods and register them with Handlebars. Unless you have some functionality that changes based on how the template is being rendered, and/or what data is being passed to the template, I wouldn't bother with that.
Here is another possibility: (from the model initialize)
initialize: function() {
this.on("change", function () {
this.set({ calculatedColumn: this.get("otherColumn") }, { silent: true });
});
},
Computed properties in Backbone
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