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
I have had the same issue. @DerickBailey is right, of course, that overriding toJSON does the job. But it also leaks into the communication with the server (see muu's comment on his answer).
So eventually, I have built a Backbone plugin to specifically handle data export to templates, and do so with a minimum of fuss: Backbone.Marionette.Export. It also deals with nested structures, takes care of circular references etc. See the docs.
Here's how it works. Include the plugin file into your project and declare
MyModel = Backbone.Model.extend({
foo: function () {
return "I am a calculated value";
},
exportable: "foo" // <-- this is the one line you have to add
});
If you are a Marionette user, you are already done at this point. foo
shows up in your templates as if it were a model attribute.
In plain Backbone views, just call myModel.export()
or myCollection.export()
instead of their toJSON counterparts when you render.
For methods taking arguments, there is an onExport
handler. Examples, again, are in the docs.