我有一个自定义绑定用于格式化百分比数字。
ko.bindingHandlers.textPercent = {
//init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
// //init logic
//},
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var val = parseFloat(ko.utils.unwrapObservable(valueAccessor()));
if ($.isNumeric(val)) {
$(element).text((val * 100).toFixed(2))+"%";
}
else {
$(element).text("#Error");
}
}
}
用法:
<span data-bind="textPercent: amount" ></span>
<span data-bind="textPercent: amount()/2" ></span>
它工作正常,但我希望能够使用不同数量的固定数字,所以我做了一个扩展器:
ko.extenders.percent = function (target, precision) {
var result = ko.computed({
read: function () {
return (target()*100).toFixed(precision)+"%";
},
write: function (newValue) {
target(parseFloat(newValue) / 100);
}
});
return result;
};
用法:
<span data-bind="text: amount.extend({ percent: 2 })" ></span>
<span data-bind="text: (amount()/2).extend({ percent: 2 })" ></span>
问题是它不适用于内联计算。
建议?