BackboneJS:迭代模型属性并更改值
BackboneJS: iterate on model attribute and change value
我想创建一个函数,具有像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
循环遍历对象,然后使用 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
实现。
演示:http://jsfiddle.net/ambiguous/ELTe5/
如果要循环访问模型的属性,请使用attributes
哈希:
// Inside your model's method
for(attr in this.attributes){
console.log(attr, this.attributes[attr]);
}
这是一个使用示例代码的 jsFiddle。
尽管这里提供的答案是正确的,并且可以做您想要的。但我认为更好的方法是为此目的使用下划线函数。对于简单的循环,您可以使用
_.each(list, iteratee, [context])
_.each(model.attributes, function(item, index, items){
console.log(item);
console.log(index);
})
您还可以根据自己的特定需求使用专用功能。就像如果你想在列表的每个元素上应用一些函数来拥有一个新的结果数组,map 可能是你的最佳选择。
_.map(list, iteratee, [context])
var newList = _.map(model.attributes, function(item, index, list){
return item * 5;
})
我建议您浏览下划线和主干的文档,以获得满足您需求的最佳功能。
相关文章:
- 如何使用jquery迭代具有相同属性的html元素并查找onclick事件
- 使用递归属性迭代保留属性结构
- 在对象上迭代.解构其键和属性并添加新的键和属性
- MongoDB属性迭代
- 迭代 DOM 中的属性
- 为什么我的jQuery .每次迭代都无法使用每个项目的属性
- 如何迭代json对象的嵌套属性并创建新的数组列表
- 创建一个生成器来迭代对象属性排列
- 在对象上迭代'的属性
- 在对象上迭代并添加新属性
- 使用 for 循环,如何迭代对象以向其添加 id 属性
- 访问特定属性并在 AngularJS 中迭代 JSON 数组
- 从数据绑定属性迭代键值对
- 如何轻松获取Javascript for loop的当前迭代属性
- BackboneJS:迭代模型属性并更改值
- 我的 JS 对象迭代在添加新属性时中断
- 如何附加具有迭代属性的元素
- 所有属性都设置为上次循环迭代值 [为什么?
- 访问并迭代模板内Kendo UI Listview的数组属性
- 对不可枚举属性进行迭代