gpt4 book ai didi

javascript - Knockout - 将值写入 ko.computed

转载 作者:行者123 更新时间:2023-11-29 10:43:34 24 4
gpt4 key购买 nike

我在 Knockout 中构建了一个数据量/数字量很大的应用程序。我目前收到错误:

Uncaught Error: Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.

当我的自定义 bindingHandler(将数字格式化为“大”形式,即 123,345,678,987)尝试写回显示计算函数值的原始输入时,就会发生这种情况。

输入元素中显示的值:

self.value = ko.computed(function(){
return self.chosenAge().population; // 'fetched' from an array.
});

绑定(bind)处理程序:

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
});
}
}
};

最佳答案

您需要在 ko.computed 函数中指定一个“写入”选项。请参阅documentation on computed observables .您的绑定(bind)处理程序与您的值无法更新无关。您的计算结果应如下所示:

self.value = ko.computed({
read: function () {
return self.chosenAge().population; // 'fetched' from an array.
},
write: function (value) {
//update your self.chosenAge().population value here
},
owner: self
});

希望这对您有所帮助。

关于javascript - Knockout - 将值写入 ko.computed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24062330/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com