Knockout - 将值写入 ko.compulated

lea*_*rrr 3 javascript knockout-2.0 knockout.js

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

未捕获错误:除非指定“写入”选项,否则无法将值写入 ko.compulated。如果您想读取当前值,请不要传递任何参数。

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

输入元素中显示的值:

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

绑定处理程序:

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
            }); 
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

Zac*_*ber 5

您需要在 ko.compulated 函数中指定“写入”选项。请参阅有关计算可观察量的文档。您的绑定处理程序与您的值更新失败无关。你的计算结果应该是这样的:

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
});
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。