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

jrs*_*nga 1 javascript backbone.js underscore.js backbone-model

我想创建一个功能,如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}
Run Code Online (Sandbox Code Playgroud)

mu *_*ort 5

您可以使用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;
}
Run Code Online (Sandbox Code Playgroud)

请注意,amount它将作为一个字符串出现,但这是获得5.00而不是5出来的唯一方法.我可能会将格式保留到模板中而不用担心这个toHTML实现.

演示:http://jsfiddle.net/ambiguous/ELTe5/