I have a custom binding that I use to format percentages.
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"); } } }
using:
<span data-bind="textPercent: amount" ></span> <span data-bind="textPercent: amount()/2" ></span>
It works fine, but I would like to use a different number of fixed digits, so I made an expander:
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; };
using:
<span data-bind="text: amount.extend({ percent: 2 })" ></span> <span data-bind="text: (amount()/2).extend({ percent: 2 })" ></span>
The problem is that it does not work with inline computing.
Suggestions?
http://jsfiddle.net/eRapL/4/
Homer source share