问题描述
在创建可观察对象后,向其添加敲除扩展器时遇到了问题.在下面的示例中,每次值按预期更改时,扩展器都在foo
上运行,但对于bar
,第一次调用时仅扩展一次.
I'm having a problem with adding a knockout extender to observables after they have been created. In the following example the extender is run on foo
every time the value changes as expected but only once, when first called, for bar
.
var viewModel = function(){
var self = this;
self.foo = ko.observable(1).extend({ numeric: 1 });
self.bar = ko.observable(1);
self.bar.extend({ numeric: 1 });
};
基本上,我正在映射一个大型JSON对象,并且想在某些属性发生映射后添加扩展器.有没有简单的方法可以做到这一点?
Essentially I am mapping a large JSON object and would like to add extenders after the mapping has occurred to some of the properties. Is there a simple way to do this?
下面是显示问题的jsfiddle:
Below is a jsfiddle showing the problem:
推荐答案
您遇到的问题是扩展程序正在创建新的可观察对象(基于它正在扩展的可观察对象).而且您第二次调用extend
时不会使用该新的observable.
The problem you have is that the extender is creating a new observable (based on the observable it's extending). And that new observable is not being used in your second call to extend
.
要解决此问题(无需更改扩展程序的代码),您可以分配,将调用extend
的响应分配到与之相同的属性中.
To fix this (without changing the code of the extender) you can assign the response from calling extend
into the same property it's called.
换句话说,在最后一行之前添加self.bar =
以便具有以下功能:
In other words, add self.bar =
in front of your last line in order to have this:
self.bar = self.bar.extend({ numeric: 1 });
这篇关于映射后应用基因剔除扩展剂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!