I have a backbone model with attributes and some helper methods that output something other than the actual attribute (for formatting for example).
However, when I call toJSON
, only the attributes are returned, so my mustache templates can't access those helper methods. Is there any way to resolve this? Or is there a different approach I should take?
Is the only way around this to create a formatted version of the attribute and update it each time that attribute changes?
Jorge, i would extend the toJSON in my own method, and give that new added json to the template.
like so:
var userModel = Backbone.Model.extend({
initialize: function(){
_.bindAll(this, 'fullname', 'toFullJSON');
},
fullname: function(){
return this.get('name') + " " + this.get('lastname');
},
toFullJSON: function(){
var json = this.toJSON();
return _.extend(json, {fullname : this.fullname()});
}
});
var user = new userModel();
u.set({name: 'John', lastname: 'Doe'});
// you will see in this console log, that the toFullJSON function returns both the toJSON properties, and your added propert(y)(ies)...
console.log(u.toFullJSON());
Make sure that the JSON is correct. If you are returning objects, there may be some back references inside them (they are not supported in JSON and will be probably omitted).