khollenbeck
khollenbeck

Reputation: 16157

Trying to Make Sense of Knockout.js Custom binding

So I am working with Knockout Custom Bindings and I have the following code:

<input type="radio" class="radio" data-bind="custombind: custombind"/>
<input type="text" class="text" data-bind="custombind: custombind"/>

--js--

var viewModel = {
        custombind: ko.observable(true)
    };
    ko.applyBindings(viewModel);

ko.bindingHandlers.custombind = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) 
    {
        alert($(element).attr('class'));
    }
}

Maybe I am misunderstanding how custom bindings work, but I would expect this to return the class names of any element with the "custombind" data-bind. Currently nothing seems to be happening. Any advice as to where I am going wrong would be appreciated. Thanks

--fiddle--

http://jsfiddle.net/tU4Fg/16/

--reference--

http://knockoutjs.com/documentation/custom-bindings.html

Upvotes: 1

Views: 451

Answers (1)

nemesv
nemesv

Reputation: 139758

Altough this is not explicity stated in the documentation but all the custom bindings should be defined before calling ko.applyBindings.

Otherwise KO won't know what to do with your custom binding when parsing the data-bind attributes.

So the following code works fine:

ko.bindingHandlers.custombind = {
    init: function(element, valueAccessor, allBindingsAccessor, 
                   viewModel, bindingContext) 
    {
        alert($(element).attr('class'));
    }
}

var viewModel = {
    custombind: ko.observable(true)
};
ko.applyBindings(viewModel);

Demo JSFiddle.

Upvotes: 1

Related Questions