Knockout.js ko.编辑时选择“如果取消,则忽略更改”

Knockout.js ko.编辑时选择“如果取消,则忽略更改”,knockout.js,observable,Knockout.js,Observable,我对柯很陌生。但是,如果我是正确的,model.firstName将观察任何更改: model.firstName = ko.observable(src.firstName) 我的问题是,如果有人在我的“编辑”屏幕(模式)上按“取消”,我不知道如何恢复到原始状态,例如: 单击以编辑 清除名字字段 单击取消 单击以再次编辑 “名字”字段为空 编辑是一个模型。我不确定如何重置它 onCancel: function () { this.show

我对柯很陌生。但是,如果我是正确的,model.firstName将观察任何更改:

model.firstName = ko.observable(src.firstName)
我的问题是,如果有人在我的“编辑”屏幕(模式)上按“取消”,我不知道如何恢复到原始状态,例如:

  • 单击以编辑
  • 清除名字字段
  • 单击取消
  • 单击以再次编辑
  • “名字”字段为空
编辑是一个
模型
。我不确定如何重置它

onCancel: function () {            
            this.show(false);
            // revert back to value provided on load?
            model.firstName(src.firstName);
        },

使用protectedObservable:

型号:

model.firstName = ko.protectedObservable(src.firstName);
model.save = function() {
   model.firstName.commit();
}
model.cancel = function() {
   model.firstName.reset();
}
HTML:

有关更多信息,请阅读本文:

您可能应该在一个单独的
js变量中维护从服务器onLoad获得的数据,以便以后可以访问它以重置它。据我所知,您可以通过更改前的
来维护以前的值(只有上次更改的值),但不需要额外的服务器调用就可以获得服务器值。我更喜欢我最初的详细信息。@ClareBarrington看起来像是一种方法(我没有进行过严格的测试),但为什么要为简单的场景编写如此奇特的代码呢。越简单越好。希望你检查了我上面的评论#实用方法。@supercool-忽略扩展名(只编写一次并保存为一个名为knockout.extensions.js的js文件),你的方法与我的方法非常相似,除了我的方法都是knockout。您必须声明一个临时变量,因为扩展正在处理我的临时变量。您还必须编写save和cancel方法。但这同样是在考虑使用扩展。而且看起来更干净,可以再次恢复,因为你的长期方法最终会有x个临时变量。但如果需要一次性修复,仍然有效。
<input data-bind="value: firstName" />
<button data-bind="click: cancel">Cancel</button>
<button data-bind="click: save">Save</button>
//wrapper to an observable that requires accept/cancel
ko.protectedObservable = function(initialValue) {
    //private variables
    var _actualValue = ko.observable(initialValue),
        _tempValue = initialValue;

    //computed observable that we will return
    var result = ko.computed({
        //always return the actual value
        read: function() {
           return _actualValue();
        },
        //stored in a temporary spot until commit
        write: function(newValue) {
             _tempValue = newValue;
        }
    }).extend({ notify: "always" });

    //if different, commit temp value
    result.commit = function() {
        if (_tempValue !== _actualValue()) {
             _actualValue(_tempValue);
        }
    };

    //force subscribers to take original
    result.reset = function() {
        _actualValue.valueHasMutated();
        _tempValue = _actualValue();   //reset temp value
    };

    return result;
};