我在视图模型中有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
});
Run Code Online (Sandbox Code Playgroud)
失败的例子是:Jsfiddle
谢谢,