问题描述
我在Knockout中构建了一个非常数据/号码的应用程序。我目前收到错误:
I've built a very data/number heavy app in Knockout. I'm currently getting the error:
当我的自定义bindingHandler发生这种情况时(将数字格式化为大形式,即123,345,678,987)尝试回写原始输入,显示计算函数的值。
This is happening when my custom bindingHandler (which formats the numbers into 'large' form, ie. 123,345,678,987) tries to write back to the original input which displays the value of a computed function.
输入元素中显示的值:
self.value = ko.computed(function(){
return self.chosenAge().population; // 'fetched' from an array.
});
绑定处理程序:
ko.bindingHandlers.largeNumber = {
init: function(element, valueAccessor) {
numberInit(element);
var value = valueAccessor();
var interceptor = ko.computed({
read: function() {
// inject number formatting
return numeral(ko.unwrap(value)).format('0,0');
},
write: function(newValue) {
// remove formatting when writing a new value
value(numeral().unformat(newValue));
}
});
// display new value in target element
if(element.tagName.toLowerCase() == 'input' ) {
ko.applyBindingsToNode(element, {
value: interceptor
});
}
else {
ko.applyBindingsToNode(element, {
text: interceptor
});
}
}
};
推荐答案
您需要指定一个'write'选项ko.computed函数。请参阅。绑定处理程序与您的值无法更新无关。你的计算结果应该是这样的:
You need to specify a 'write' option in your ko.computed function. Please see the documentation on computed observables. Your binding handler has nothing to do with your value failing to update. Your computed should look something like this:
self.value = ko.computed(function(){
read: function () {
return self.chosenAge().population; // 'fetched' from an array.
},
write: function (value) {
//update your self.chosenAge().population value here
},
owner: self
});
希望这有帮助。
这篇关于Knockout - 将值写入ko.computed的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!