2014-02-28 134 views
0

我有一个selectedCustomer(customer)observable,其中客户有3个属性:Fname,LName,Age。敲除恢复更改

我将这3个属性的数据绑定到三个文本输入并允许用户编辑它们。我如何取消这些更改并将这三个属性恢复到原始状态?

我可以使用,使这一个克隆:

VAR custCache = ko.observable(ko.mapping.toJS(客户));

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

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

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

感谢, 凯文

回答

0

在构建数据点取2个观测值:

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

绑定第二个以避免用户输入反映了控制。

如果他们取消你可以像重置值:

selectedCustomer(originalSelectedCustomer()); 

如果他们接受,从selectedCustomer将数据保存到存储。

你或许应该让你的客户对象的内部属性都是可观察的。

1

瑞恩·尼迈耶已经撰写了有关这一主题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' 
+0

这应该被标记为正确答案。 –