2013-04-21 38 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

相關問題