【问题标题】:ko.obserable ignore change if cancelled selected on editko.observable 如果在编辑时选择取消则忽略更改
【发布时间】:2015-11-12 09:52:54
【问题描述】:

我对 KO 很陌生。但是,如果我是正确的,model.firstName 会观察到任何变化:

model.firstName = ko.observable(src.firstName)

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

  • 点击编辑
  • 清除名字字段
  • 点击取消
  • 点击再次编辑
  • 名字字段为空

编辑是model。我不确定如何重置它?

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

【问题讨论】:

  • 您可能应该将您从服务器 onLoad 获得的数据保存在一个单独的 js variable 中,以便您以后可以访问它来重置它。据我所知,您可以通过beforeChange 维护以前的值(只有最后一次更改的值),但是无需额外的服务器调用即可获得服务器值,我更喜欢我的初始细节。

标签: knockout.js observable


【解决方案1】:

使用受保护的Observable:

型号:

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

HTML:

<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;
};

有关更多信息,请阅读这篇文章: KnockMeOut

【讨论】:

  • @ClareBarrington 看起来像是一种方法(我还没有测试过),但为什么要为简单的场景编写如此花哨的代码。越简单越好。希望您检查了我在#pragmatic approach 上面的评论。
  • @supercool - 忽略扩展名(它被编写一次并保存为 js 文件,例如,knockout.extensions.js)你的方法非常相似,除了我的都是淘汰赛。您必须声明一个临时变量,因为我的扩展正在照顾。您还必须编写保存和取消方法。但这又是在使用扩展程序。并且看起来更干净,并且可以再次使用,因为您的长期方式最终会得到 x 数量的临时变量。但如果需要一次修复仍然有效。
猜你喜欢
  • 2017-02-11
  • 1970-01-01
  • 2011-07-12
  • 1970-01-01
  • 2010-12-14
  • 1970-01-01
  • 2012-06-10
  • 2014-12-05
  • 2016-05-29
相关资源
最近更新 更多