如何使用undo创建可观察数组?

我正在尝试将淘汰JS添加到我们网站上的搜索页面。 目前,您打开了一个jQuery对话框,其中包含许多可以选择的条件复选框。

有多个对话框,有多种类型的标准。 当您打开对话框时,复选框只有在您点击“更新”按钮后才会生效,如果您单击取消或只是关闭窗口,您所做的更改将被还原,对话框将设置为其以前的状态。

我读了这个和其他一些post。 然而,这似乎只适用于ko.observable ,我似乎无法使用ko.observableArray

有没有人完成这个或有任何想法?

我想做的一个例子:

HTML:

 
Cancel Update

使用Javascript:

 var viewModel = { genders: ko.observableArrayWithUndo([]) }; ko.applyBindings(viewModel); $('#buttonCancel').click(function(){ viewModel.genders.resetChange(); }); $('#buttonUpdate').click(function(){ viewModel.genders.commit(); return false; }); 

这将是一种方法:

 //wrapper to an observableArray of primitive types that has commit/reset ko.observableArrayWithUndo = function(initialArray) { var _tempValue = ko.observableArray(initialArray.slice(0)), result = ko.observableArray(initialArray); //expose temp value for binding result.temp = _tempValue; //commit temp value result.commit = function() { result(_tempValue.slice(0)); }; //reset temp value result.reset = function() { _tempValue(result.slice(0)); }; return result; }; 

您可以将复选框绑定到yourName.temp,将UI的其他部分绑定到yourName。

以下是一个示例: http : //jsfiddle.net/rniemeyer/YrfyW/

slice(0)是获取数组的浅表副本(甚至只是slice())的一种方法。 否则,您将对对同一数组的引用执行操作。

鉴于HTML类似于:

 

您可以使用类似于此的一些Knockout代码,基本上将撤消堆栈保存为每次更改后的状态的JSON字符串表示。 基本上,您创建一个伪的依赖observable来订阅视图中的所有属性,或者您可以手动迭代并订阅每个属性。

 //current state would probably come from the server, hard coded here for example var currentState = JSON.stringify({ firstName: 'Paul', lastName: 'Tyng', text: 'Text' }) , undoStack = [] //this represents all the previous states of the data in JSON format , performingUndo = false //flag indicating in the middle of an undo, to skip pushing to undoStack when resetting properties , viewModel = ko.mapping.fromJSON(currentState); //enriching of state with observables //this creates a dependent observable subscribed to all observables //in the view (toJS is just a shorthand to traverse all the properties) //the dependent observable is then subscribed to for pushing state history ko.dependentObservable(function() { ko.toJS(viewModel); //subscribe to all properties }, viewModel).subscribe(function() { if(!performingUndo) { undoStack.push(currentState); currentState = ko.mapping.toJSON(viewModel); } }); //pops state history from undoStack, if its the first entry, just retrieve it window.undo = function() { performingUndo = true; if(undoStack.length > 1) { currentState = undoStack.pop(); ko.mapping.fromJSON(currentState, {}, viewModel); } else { currentState = undoStack[0]; ko.mapping.fromJSON(undoStack[0], {}, viewModel); } performingUndo = false; }; ko.applyBindings(viewModel); 

我在这里有一个带有淘汰赛的N级撤消样本:

http://jsfiddle.net/paultyng/TmvCs/22/

您可以根据自己的需要进行调整。