2013-04-21 116 views
0

我正在使用Knockout并将可观察集合绑定到标记。如何将计算属性添加到集合?

如果我可以为集合中的每个项目添加计算函数,那将是非常好的,但我不确定如何在Knockout中正确执行此操作。

例如,假设这种模式:

var model = { 
    'persons' : [ 
     { firstName: "John", lastName: "Smith" }, 
     { firstName: "Sgt.", lastName: "Shiney-Sides" }, 
     { firstName: "Rusty", lastName: "Schacklefurt" } 
    ] 
}; 

ko.applyBindings(model); 

我想补充一个fullName计算功能地连接了第一个和最后一个名称。

回答

1

@ jonathanconway的答案是正确的,但有点落后,它对大集合的内存使用量很重,将该类的声明从create方法移出。

然后,只需调用从创建函数的构造类似

create: function (options) { 
    return new Person(options); 
} 

为了节省更多的内存,你可以移动计算的原型声明。

2

您可以使用Knockout Mapping plugin来实现此目的。

的代码会是这个样子:

var model = { 
    'persons' : [ 
     { firstName: "John", lastName: "Smith" }, 
     { firstName: "Sgt.", lastName: "Shiney-Sides" }, 
     { firstName: "Rusty", lastName: "Schacklefurt" } 
    ] 
}; 

// specifies the create callback for the 'persons' property 
var mappingOptions = { 
    'persons': { 
     // overriding the default creation/initialization code 
     create: function (options) { 
      var Person = function() { 
       this.fullName = ko.computed(function() { 
        return this.firstName() + ' ' + this.lastName(); 
       }, this); 

       // let the ko mapping plugin continue to map out this object, so the rest of it will be observable 
       ko.mapping.fromJS(options.data, {}, this); 
      }; 
      return new Person(); 
     } 
    } 
}; 

model = ko.mapping.fromJS(model, mappingOptions); 

ko.applyBindings(model); 

感谢Allen Ricethis solution