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 p
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.