我在View-Model中有3个可观察的变量,并希望输出以格式化值。但是,我不想为它们编写计算方法,因为它们是相同的。重复使用代码的最佳方法是什么?谢谢。
我要实现的代码是:
this.formattedPrice = ko.computed({
read: function () {
return '$' + this.price().toFixed(2);
},
write: function (value) {
// Strip out unwanted characters, parse as float, then write the raw data back to the underlying "price" observable
value = parseFloat(value.replace(/[^.d]/g, ""));
this.price(isNaN(value) ? 0 : value); // Write to underlying storage
},
owner: this
});
,失败的示例在:jsfiddle
谢谢,
以下是您可以重复使用的几种方法。
如果您想在视图模型中处理此操作,那么一个不错的选择是创建一个扩展程序,该扩展名将计算为可观察到的格式计算为原件的"亚近距离"。您可以使用扩展程序或通过添加到共享的fn
对象中扩展可观察到的物品。我更喜欢后者。
因此,您可以将一个函数添加到可观察到的 withCurrencyFormat
。看起来像:
ko.observable.fn.withCurrencyFormat = function(precision) {
var observable = this;
observable.formatted = ko.computed({
read: function (key) {
return '$' + (+observable()).toFixed(precision);
},
write: function (value) {
value = parseFloat(value.replace(/[^.d]/g, ""));
observable(isNaN(value) ? null : value); // Write to underlying storage
}
});
return observable;
};
现在,您可以说:
self.week1Amount = ko.observable(w1).withCurrencyFormat(2);
self.week2Amount = ko.observable(w2).withCurrencyFormat(2);
self.week3Amount = ko.observable(w3).withCurrencyFormat(2);
并在UI中与之绑定,例如:
<td><input data-bind="value: week1Amount.formatted" /></td>
<td><input data-bind="value: week2Amount.formatted" /></td>
<td><input data-bind="value: week3Amount.formatted" /></td>
示例在这里:http://jsfiddle.net/rniemeyer/xskjn/
另一个选择是将其转移到绑定中,因此您可以单独使用视图模型。这将使用类似的代码,但是在自定义绑定处理程序中看起来像:
ko.bindingHandlers.valueAsCurrency = {
init: function(element, valueAccessor) {
var observable = valueAccessor(),
formatted = ko.computed({
read: function (key) {
return '$' + (+observable()).toFixed(2);
},
write: function (value) {
value = parseFloat(value.replace(/[^.d]/g, ""));
observable(isNaN(value) ? null : value); // Write to underlying storage
},
disposeWhenNodeIsRemoved: element
});
//apply the actual value binding with our new computed
ko.applyBindingsToNode(element, { value: formatted });
}
};
因此,在绑定处理程序中,我们创建了计算机,然后使用value
绑定。
现在,您的视图模型不需要更改,并且您将在UI中绑定:
<td><input data-bind="valueAsCurrency: week1Amount" /></td>
<td><input data-bind="valueAsCurrency: week2Amount" /></td>
<td><input data-bind="valueAsCurrency: week3Amount" /></td>
示例此处:http://jsfiddle.net/rniemeyer/sd6y4/