Knockout JS中的多个扩展器无法正常工作 [英] Multiple Extenders in Knockout JS not working
问题描述
只是在KO找到我的路,所以请保持温和!
Just finding my way in KO, so please be gentle!
每个扩展器都可以工作,但当我链接它们时,第一个(重置)不会发射。
Individually each extender works, but when i chain them, the first one (reset) doesnt fire.
Javascript:
ko.extenders.reset = function (target) {
var initialValue = target();
target.reset = function () {
target(initialValue);
}
return target;
}
ko.extenders.numeric = function (target, precision) {
//create a writeable computed observable to intercept writes to our observable
var result = ko.computed({
read: target, //always return the original observables value
write: function (newValue) {
var current = target(),
roundingMultiplier = Math.pow(10, precision),
newValueAsNum = isNaN(newValue) ? 0 : parseFloat(+newValue),
valueToWrite = Math.round(newValueAsNum * roundingMultiplier) / roundingMultiplier;
//only write if it changed
if (valueToWrite !== current) {
target(valueToWrite);
} else {
//if the rounded value is the same, but a different value was written, force a notification for the current field
if (newValue !== current) {
target.notifySubscribers(valueToWrite);
}
}
}
}).extend({
notify: 'always'
});
//initialize with current value to make sure it is rounded appropriately
result(target());
//return the new computed observable
return result;
};
function AppViewModel(first, last) {
this.firstName = ko.observable(first).extend({
reset: true
});
this.lastName = ko.observable(last).extend({
reset: true,
numeric: 0
});
self.resetAll = function () {
for (key in self) {
if (ko.isObservable(self[key]) && typeof self[key].reset == 'function') {
self[key].reset()
}
}
}
}
ko.applyBindings(new AppViewModel());
HTML:
1 extender (works):<input data-bind='value: firstName' /><br>
2 extenders (doesnt work)<input data-bind='value: lastName' /><br>
<input type="button" value="Reset All" data-bind="click:resetAll" id="ResetInvoiceButton" />
小提琴:
http://jsfiddle.net/sajjansarkar/vk4x2/1/
推荐答案
因为你的数字
扩展器返回一个新的计算扩展器的顺序确实重要。
Because your numeric
extender returns a new computed the order of your extenders does matter.
在您当前的设置中,您的重置
扩展程序首先运行并添加重置函数到你原来的observable然后 numeric
运行,所以它用一个全新的计算observable覆盖你的reset enhancedobservable。
In your current setup your reset
extender runs first and it adds the reset function to your original observable but then the numeric
runs so it overrides your "reset enhanced" observable with a completely new computed observable.
所以你只需要按照正确的顺序执行你的扩展器:
So you just need to execute your extenders in the correct order:
this.lastName = ko.observable(last)
.extend({ numeric: 0 })
.extend({ reset: true });
演示 JSFiddle 。
请注意,如果您想为扩展器订购特定订单,则需要在单独的扩展$ c $中应用它们c>否则不会保证执行订单属于属性的顺序。
Note that if you want to have a specific order for your extenders you need to apply them in separate extend
calls otherwise the execution order is not guarantied to be in the order of the properties.
这篇关于Knockout JS中的多个扩展器无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!