knockout.jsko-custom-binding

Custom binding valueAccessor has unexpected result


I am stumped by the following behavior in a custom binding of knockout.js:

ko.bindingHandlers.customBinding = {
    update: function(element, valueAccessor, allBindingsAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        console.log( JSON.stringify(value) );
    }
}

ko.applyBindings({
    someText: ko.observable("inital value")
});

and

<input type="text" data-bind="value: someText, customBinding: {some: 'option'}">

The valueAccessor() should give me the view model property that is bound to the value of the element (i.e. the observable someText). To quote the docs:

valueAccessor — A JavaScript function that you can call to get the current model property that is involved in this binding. Call this without passing any parameters (i.e., call valueAccessor()) to get the current model property value.

However, what it really does is return the binding value, i.e. {some: 'option'}.

What am I missing?

See http://jsfiddle.net/j5y8H/


Solution

  • You need to pass the model property you want for your valueAccessor in your custombinding call. In your case, you want the model property 'someText' :

    <input type="text" data-bind="value: someText, customBinding: someText">
    

    See http://jsfiddle.net/j5y8H/1/