请告诉我,在视图中数据处理的最佳实践是什么?
示例:我有一个User模型,并且有字段age。在这个领域,是一个用户的时代。它是一个整数值-月份的数量。我如何在我的模板中实现这一点:
我可以把这个助手方法存放在哪里?模板内部是不正确的方式。否则,我需要执行一些函数来生成正确的模型json。(不是model.toJSON())或扩展现有的JSON.或者..。
做这件事最好的方法是什么?
谢谢。
发布于 2012-02-05 23:50:28
有两种方法。
您可以将其放在模型上,然后将模型传递给模板--这意味着,在模板中,您必须使用model.get('age')等来获取属性,但它也使使用该模型的助手方法成为可能。
另一个选择是拥有某种全局帮助集合,以后您可以像helpers.verboseAge(age)这样从模板中访问它(不知道您正在使用的模板脚本是什么,所以它可能是it.age、this.age、age……但你知道这个主意。
发布于 2012-02-05 23:54:10
几个月前,我回答了一个类似的问题:在这个问题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()。
https://stackoverflow.com/questions/9153913
复制相似问题