【问题标题】:Knockout reverting changes淘汰赛还原更改
【发布时间】:2014-04-01 07:47:53
【问题描述】:

我有一个 selectedCustomer(customer) observable,其中客户有 3 个属性:Fname、LName、Age。

我将这 3 个属性数据绑定到三个文本输入,并允许用户对其进行编辑。如何取消更改并将这三个属性恢复为原始状态?

我能够使用以下方法对其进行克隆:

var custCache = ko.observable(ko.mapping.toJS(customer));

我不想像下面那样进行手动映射,因为当你的对象有很多属性和其他对象的数组时,这会很麻烦。

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

那么当用户取消更改时,如何将值放回客户对象?如何循环这些属性并复制它们?

谢谢, 凯文

【问题讨论】:

    标签: knockout.js


    【解决方案1】:

    Ryan Niemeyer 写过关于这个主题的文章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'
    

    【讨论】:

      【解决方案2】:

      在构建数据时创建两个 observable:

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

      将第二个绑定到控件,以便反映用户输入。

      如果他们取消,您可以使用以下内容重置值:

      selectedCustomer(originalSelectedCustomer());
      

      如果他们接受,请将数据从 selectedCustomer 持久化到您的存储中。

      您可能应该将客户对象的内部属性也设为所有可观察对象。

      【讨论】:

        猜你喜欢
        • 2013-09-10
        • 2018-03-30
        • 1970-01-01
        • 1970-01-01
        • 2022-10-17
        • 1970-01-01
        • 1970-01-01
        • 2017-10-26
        • 1970-01-01
        相关资源
        最近更新 更多