You have multiple problems with your current approach:
element.tagName
returns INPUT, etc so you need to take care of the casing when doing the comparing.var value = ko.unwrap(valueAccessor());
you are unwrapping your observable so in your computed you are using its value and not the function itself. So you just needvar value = valueAccessor();
and you need to callko.unwrap
in your computedread
method.You don't just need to format but you need to "unformat" in the
write
method, but yourformatLargeNumber
only do the format direction.You have applied
value
and yourlargeNumber
on the same input which make the two bindings interfering with each otherDon't write the formatting code yourself just use a library which already does this like: http://numeraljs.com/
So here is the corrected version of your binding using numeraljs:
ko.bindingHandlers.largeNumber = {
init: function(element, valueAccessor) {
var value = valueAccessor();
var interceptor = ko.computed({
read: function() {
return numeral(ko.unwrap(value)).format('0,0');
},
write: function(newValue) {
value(numeral().unformat(newValue));
value.valueHasMutated();
}
}).extend({notify: 'always'});
if(element.tagName.toLowerCase() == 'input' )
ko.applyBindingsToNode(element, {
value: interceptor
});
else
ko.applyBindingsToNode(element, {
text: interceptor
});
}
}
And use it like this:
<input data-bind="largeNumber: testVal">
Demo JSFiddle.