2014-02-28 59 views
0

我有一個selectedCustomer(customer)observable,其中客戶有3個屬性:Fname,LName,Age。敲除恢復更改

我將這3個屬性的數據綁定到三個文本輸入並允許用戶編輯它們。我如何取消這些更改並將這三個屬性恢復到原始狀態?

我可以使用,使這一個克隆:

VAR custCache = ko.observable(ko.mapping.toJS(客戶));

我不想像下面那樣進行手動映射,因爲當你的對象有很多合適的屬性和其他對象的數組時,這可能會很麻煩。

selectedCustomer().Fname = custCache().Fname; 
selectedCustomer().Lname = custCache().Lname; 
selectedCustomer().Age= custCache().Age; 

那麼當用戶取消更改時,如何將值返回給客戶對象?我如何循環這些屬性並複製它們?

感謝, 凱文

回答

0

在構建數據點取2個觀測值:

originalSelectedCustomer = ko.observable(customer); 
selectedCustomer = ko.observable(customer); 

綁定第二個以避免用戶輸入反映了控制。

如果他們取消你可以像重置值:

selectedCustomer(originalSelectedCustomer()); 

如果他們接受,從selectedCustomer將數據保存到存儲。

你或許應該讓你的客戶對象的內部屬性都是可觀察的。

1

瑞恩·尼邁耶已經撰寫了有關這一主題here

然而另一種常見的方法是創建一個knockout extender

它是這樣的:

ko.extenders.revertable = function(obs, option) { 
    // Change this if you want to use something other than _.clone 
    // as your clone function 
    var cloneFn = _.clone; 

    obs.originalValue = cloneFn(obs()); 
    obs.silentUpdate = ko.observable(false); 
    obs.isDirty = ko.observable(false); 

    obs.revert = function() { 
    obs.silentUpdate(true); 
    obs(cloneFn(obs.originalValue)); 
    obs.silentUpdate(false); 
    obs.isDirty(false); 
    }; 

    obs.update = function(value) { 
    obs.silentUpdate(true); 

    if (_.size(arguments) > 0) { 
     obs(value); 
    } 

    obs.originalValue = cloneFn(obs()); 
    obs.silentUpdate(false); 
    obs.isDirty(false); 
    }; 

    obs.subscribe(function(newValue) { 
    if (!ko.unwrap(obs.silentUpdate)) { 
     obs.isDirty(true); 
    } 
    }); 

    return obs; 
} 

我用下劃線在我的例子,但你可以,如果你不使用你的項目強調定製。

使用這樣的:

var myValue = ko.observable('original'); 
myValue = myValue.extend({ revertable: {} }); 

myValue('updated'); 
myValue.revert(); 

console.log(myValue()); // logs 'original' 
+0

這應該被標記爲正確答案。 –