1

I'm trying to create custom binding for special number formatting.

    ko.bindingHandlers['valueTest'] = {
        'init': function (element, valueAccessor, allBindingsAccessor) {
            var valueUpdateHandler = function () {
                var modelValue = valueAccessor();
                var elementValue = ko.selectExtensions.readValue(element);
                ko.expressionRewriting.writeValueToProperty(modelValue, allBindingsAccessor, 'value', elementValue);
            }

            ko.utils.registerEventHandler(element, "change", valueUpdateHandler);
        },
        'update': function (element, valueAccessor) {
            var newValue = ko.utils.unwrapObservable(valueAccessor());
            var elementValue = ko.selectExtensions.readValue(element);

            if (newValue !== elementValue) {
                ko.selectExtensions.writeValue(element, newValue.toFixed(2).replace(".", ","));
            }
        }
    }; 

Also available on fiddle http://jsfiddle.net/PAFTR/11/

But it fails on updating (firebug says: TypeError: ko.expressionRewriting.writeValueToProperty is not a function).

JotaBe
  • 38,030
  • 8
  • 98
  • 117
edgecrusher
  • 143
  • 6

1 Answers1

2

Looks like this is better fitted in a observable extender? Check this fiddle i've done

http://jsfiddle.net/yEgmt/

Its used like

this.number = ko.observable().extend({ numeric: true })
Anders
  • 17,306
  • 10
  • 76
  • 144
  • I'm aware of observable extenders, but I have cases when I'm providing complex JSON to single ko.observable or ko.observableArray. So please, teach me how to create custom binding :) – edgecrusher Nov 27 '12 at 05:55
  • Please read the [official documentation](http://knockoutjs.com/documentation/custom-bindings.html) how to create a custom bindings – Pavlo Nov 27 '12 at 19:26