BackboneJS:迭代模型属性并更改值

BackboneJS: iterate on model attribute and change value

本文关键字:属性 迭代 模型 BackboneJS      更新时间:2023-09-26

我想创建一个函数,具有像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;
})

我建议您浏览下划线和主干的文档,以获得满足您需求的最佳功能。