我在viewmodel中有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 });
失败的例子是:http://jsfiddle.net/EBxy4/68/
谢谢,
解决方法
这里有几种方法可以使这个可重用.
如果你想在你的视图模型中处理这个,那么一个很好的选择是创建一个扩展,将格式化的计算的可观察值存储为原始的“sub-observable”.您可以使用extenders扩展可观察值,或者按照here所述添加到共享fn对象.我更喜欢后者.
所以,你可以添加一个函数到observables调用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 }); } };
因此,在绑定处理程序中,我们创建我们的计算,然后使用值绑定.
现在,您的视图模型不需要任何更改,您将在UI中绑定,如:
<td><input data-bind="valueAsCurrency: week1Amount" /></td> <td><input data-bind="valueAsCurrency: week2Amount" /></td> <td><input data-bind="valueAsCurrency: week3Amount" /></td>