我有“钱”的自定义绑定。它将在开头插入一个美元符号,并为小数点左边的每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”过去曾在视图中显示,但现在我正在显示“LYMonthSalesComputed”。
现在,“write”不会将值写入LYMonthSales属性。 (调用我的保存时,原始值仍然存在)
答案 0 :(得分:1)
我想你想要writeblae computed observable。这将允许您指定用于将新值写入计算值的逻辑。像这样:
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
});