I am creating a very multi-fertile application in KnockoutJS, and I want to be able to format large numbers so that they are separated by commas and beautiful on the eye (xxx, xxx).
As you will see from the scripts below, I have this by wrapping the bound value inside the format function with a simple RegEx, but the problem is that it overwrites the value inside the input and inserts ',' into the base value.
Larger numbers are used later in the application, so to prevent NaN errors, I had to assign a data attribute to an input value containing an unsigned "," value, and this value is stored in sessionStorage.
I feel like I have greatly inflated my HTML markup and believe that what I want to achieve is possible with bindHandler, but my binding handler is not quite there.
Fiddle: http://jsfiddle.net/36sD9/2
formatLargeNumber = function (number) { if (typeof (number) === 'function') { return number().toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); } } ko.bindingHandlers.largeNumber = { init: function(element, valueAccessor) { var value = ko.unwrap(valueAccessor()); var interceptor = ko.computed({ read: function() { return formatLargeNumber(value); }, write: function(newValue) { value(reverseFormat(newValue)); } }); if(element.tagName == 'input' ) ko.applyBindingsToNode(element, { value: interceptor }); else ko.applyBindingsToNode(element, { text: interceptor }); } }
Any ideas?
leaksterrr
source share