我之前给了一个回答类似的问题几个月。 发现它在这个问题backbone toJSON with helper methods
它归结为添加方法的JSON,你去之前模板
是这样的:
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();
user.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(user.toFullJSON());
你可以做的另一件事是覆盖的toJSON方法
这样的:
var myModel = Backbone.Model.extend({
// other methods and functions go here...
toJSON: function (attr) {
var defaultJSON = Backbone.Model.prototype.toJSON.call(this, attr)
return _.extend(defaultJSON, {calculateAge : this.calculateAge()});
},
calculateAge: function(){
// here you calculate the years and what not, then return it.
}
});
,做这将是给模型到您的模板代替的第三条道路。 toJSON()返回。那么你可以在你的模板中调用model.CalculateAge()。