如何使用撤消创建可观察的数组? [英] How to create an observable array with undo?

查看:65
本文介绍了如何使用撤消创建可观察的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to add knockout JS to a search page on our website. Currently you open up a jQuery dialog box, which has a number of checkboxes of criteria that you can select.

有多个对话框,其中包含多种类型的条件.打开对话框时,直到单击更新"按钮,复选框才生效;如果单击取消"或仅关闭窗口,则所做的更改将被还原,并且对话框将设置为以前的状态.

There are multiple dialogs with multiple types of criteria. When you open the dialog, the checkboxes do not take effect until you hit an "Update" button, if you click cancel or just close the window, the changes you made get reverted and the dialog is set to its former state.

我阅读了和其他一些帖子.但是,这似乎仅适用于ko.observable,而我似乎无法使其适用于ko.observableArray.

I read this and a few other posts. However this seems to only work with ko.observable, and I cannot seem to get it to work with ko.observableArray.

有人做到了或有什么想法吗?

Has anyone accomplished this or have any ideas?

我想做的事的例子:

HTML:

<form>
    <div>
        <div>
            <label><input type="checkbox" data-bind="checked: genders" value="1" />Male</label>
            <label><input type="checkbox" data-bind="checked: genders" value="2" />Female</label>
        </div>
    </div>
    <a id="buttonCancel">Cancel</a>
    <a id="buttonUpdate">Update</a>
</form>
<div data-bind="text: ko.toJSON(viewModel)"></div>

JavaScript:

Javascript:

var viewModel = {
    genders: ko.observableArrayWithUndo([])
};

ko.applyBindings(viewModel);

$('#buttonCancel').click(function(){
   viewModel.genders.resetChange();
});

$('#buttonUpdate').click(function(){
    viewModel.genders.commit();
    return false;
});

推荐答案

这里将是一种解决方法:

Here would be one way to approach it:

//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.

You would bind your checkboxes to yourName.temp and the other part of your UI to just yourName.

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

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

The slice(0) is one way to get a shallow copy of an array (or even just slice()). Otherwise, you would be performing operations on a reference to the same array.

这篇关于如何使用撤消创建可观察的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆