淘汰赛还原变革

时间:2014-02-28 10:47:54

标签: knockout.js

我有一个selectedCustomer(customer)observable,其中customer有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;

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

谢谢, 凯文

2 个答案:

答案 0 :(得分: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'

答案 1 :(得分:0)

在构建数据时制作两个可观察对象:

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

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

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

selectedCustomer(originalSelectedCustomer());

如果他们接受,请将selectedCustomer中的数据保存到您的存储空间。

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

相关问题