我有一個在網格中呈現的observableArray。當用戶點擊一行時,會彈出一個對話框,讓用戶能夠編輯選定的項目。我想讓用戶能夠更新或取消他們的更改,但由於所選記錄是可觀察的,所以立即進行更改。當用戶用KnockoutJS提交而非自動提交時,在observableArray中更新記錄
如何將所選記錄與observableArray分開,以便僅在用戶單擊「更新」時更新數據?
這裏是我的問題的一個簡化版本 - 我fiddle
function Type(data) {
this.id = data.id;
this.name = ko.observable(data.name);
};
function Location(data) {
this.id = data.id;
this.name = ko.observable(data.name);
this.state = ko.observable(data.state);
this.headline = ko.observable(data.headline);
this.type = ko.observable(new Type(data.type));
};
function ViewModel() {
var self = this;
self.types = types;
self.locations = ko.observableArray(ko.utils.arrayMap(seedData, function(item) {
return new Location(item);
}));
self.selectedLocation = ko.observable();
self.edit = function(item) {
self.selectedLocation(item);
};
self.cancel = function() {
self.selectedLocation(null);
};
self.update = function(item) {
//do something here to push updated Location to locations observableArray
};
}
你應該明白,你的'selectedLocation'觀察到將包含** **實際位置的項目,你作中將會在相同的實例反映了所有的編輯。這是因爲JS中的對象是通過引用分配的,而不是按值分配的。閱讀關於*編輯器*模式實施在這裏:http://www.knockmeout.net/2013/01/simple-editor-pattern-knockout-js.html –