Jor*_*eña 1 mustache backbone.js
我有一个带有属性的骨干模型和一些辅助方法,它们输出的不是实际属性(例如用于格式化).
但是,当我调用时toJSON
,只返回属性,因此我的胡子模板无法访问这些辅助方法.有什么方法可以解决这个问题吗?或者我应该采取不同的方法?
是唯一的方法来创建属性的格式化版本,并在每次属性更改时更新它?
Jorge,我会在我自己的方法中扩展toJSON,并将新添加的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();
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());
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2814 次 |
最近记录: |