我想创建一个函数,其功能类似于 toJSON()
的返回和编辑模型的功能。
我的问题是如何迭代模型的属性并编辑您选择的属性的特定值。
如果有模型,例如:
Item = Backbone.Model.extend({
defaults: {
name: '',
amount: 0.00
},
toHTML: function(){
// i think this is the place where
// where i can do that function?
//
console.log(this.attribute)
}
});
var item = new Item;
item.set({name: 'Pencil', amount: 5}):
item.toJSON();
-> {name: 'Pencil', amount: 5}
// this is the function
item.toHTML();
-> {name: 'Pencil', amount: 5.00}
最佳答案
您可以使用 for ... in
loop 遍历一个对象然后使用 toFixed
格式化数字:
toHTML: function() {
var attrs = { }, k;
for(k in this.attributes) {
attrs[k] = this.attributes[k];
if(k === 'amount')
attrs[k] = attrs[k].toFixed(2);
}
return attrs;
}
请注意,amount
将以字符串形式出现,但这是获得 5.00
而不是 5
的唯一方法。我可能会将格式设置留给模板,而不会为这个 toHTML
实现而烦恼。
关于javascript - 主干JS : iterate on model attribute and change value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19042289/