取消计算列的自定义绑定

Knockout custom binding to a computed column

本文关键字:自定义 绑定 计算 取消      更新时间:2024-04-04

我有一个"money"的自定义绑定。它将在开头插入一个美元符号,并为小数点后每3位添加一列。此外,同一列是ko.computed列。

我遇到的问题是,我必须将该列格式化为setter:

myColumn.myValue(functionToGenerateNewValue(parameter)()); //notice the parens after the function to actually retrieve the value

以便能够正确地进行货币绑定。但是,如果我想让计算的值在飞行中发挥作用,那么它必须这样设置:

myColumn.myValue = ko.computed(functionToGenerateNewValue(parameter));

这是绑定货币的代码:

var cleanInput = function (value) {
    return parseFloat(value.replace(/[^0-9.-]/g, ''));
}
ko.bindingHandlers.money = {
    init: function (elm, valueAccessor) {
        $(elm).change(function () {
            valueAccessor()(cleanInput(elm.value));
        }).addClass('money');
    },
    update: function (elm, valueAccessor, allBindingsAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor())
        $elm = $(elm),
        method = $elm.is(":input") ? "val" : "html";
        $elm[method](formatCurrency(value));
    }
};

当它被调用为计算值时,elm.value是失败的部分,因为它包含一个函数而不是一个值。

知道如何将这两种实现混合在一起吗?

编辑:这是我的新版本,我仍然有点坚持…

if (goalMonth > viewModel.LastProcessedMonth()) {
                    if (goal.LYMonthSales() === goal.LYMonthSalesActual()) {
                        goal.LYMonthSales = ko.computed({
                            read: generateTotalSales(goalMonth),
                            write: function (newValue) {
                                goal.LYMonthSales(newValue);
                            }
                        });
                        goal.LYMonthSalesComputed = ko.computed({
                            read: goal.LYMonthSales,
                            write: function (newValue) {
                                goal.LYMonthSales(newValue);
                            }
                        });
                        //goal.LYMonthSales(generateTotalSales(goalMonth)());
                    }
                    goal.LYMonthSalesActual = ko.computed(generateTotalSales(goalMonth));
                    //goal.LYMonthSalesActual(generateTotalSales(goalMonth)());
                }

"LYMonthSales"过去显示在视图上,但现在我显示的是"LYMonth SalesComputed"。

现在,"写入"不是将值写入LYMonthSales属性。(调用我的save时,原始值仍然存在)

我想你想要一个计算可观察的writeblae。这将允许您指定将新值写入计算值的逻辑。类似这样的东西:

myColumn.myValue = ko.computed({
    read: functionToGenerateNewValue(parameter),
    write: function(newVal){
       //now manually provide the logic to handle a new value
    },
    owner: myColumn //optional - will cause the `this` value to be correct
});