骨干的toJSON与辅助方法 [英] backbone toJSON with helper methods
问题描述
我有属性和一些辅助方法骨干模型比实际属性(例如格式化)等输出的东西。
I have a backbone model with attributes and some helper methods that output something other than the actual attribute (for formatting for example).
然而,当我打电话的toJSON
,只返回的属性,所以我的胡子模板无法访问这些辅助方法。有什么办法解决呢?还是有不同的方法,我应该走?
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?
推荐答案
豪尔赫,我会延长的toJSON在我自己的方法,并给出新添加的JSON到模板。
Jorge, i would extend the toJSON in my own method, and give that new added json to the template.
像这样:
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());
这篇关于骨干的toJSON与辅助方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!