2017-05-28 156 views
0

我有一個小演示fiddle,我希望列表更新,當我更改數組項目的名稱屬性。據我所知,我必須把所有的項目都作爲可觀察項目。我該怎麼做?使可觀察陣列的所有項目可觀察

this.allItems = ko.observableArray([{name:"Fries"}, {name:"Eggs Benedict"}, {name:"Ham"}, {name:"Cheese"}]); 
+1

你必須使用'mapping'插件:'ko.mapping.fromJS([{...}])'(http://knockoutjs.com/documentation/plugins- mapping.html) – haim770

回答

1

您定義返回一個對象,具有可觀察到的name性的方法:

var makeNameObservable = function(obj) { 
    return { 
    name: ko.observable(obj.name) 
    }; 
}; 

然後可以使用map改變你的陣列:

this.allItems = ko.observableArray([ /* ... */ ].map(makeNameObservable)); 

通常,在淘汰賽的應用,這些對象被稱爲視圖模型並使用構造函數實例化。例如:

var Food = function(name) { 
    this.name = ko.observable(name); 
}; 

Food.fromObj = function(obj) { 
    return new Food(obj.name); 
}; 

// Elsewhere: 
var myFoods = [ { name: "Fries" } ].map(Food.fromObj);