knockout.jsko-custom-binding

knockout.js calling custom binding function


I've found an unusual code, but I don't understand how to call this custom binding function and how is that supposed to work. So here is my code:

ViewModel:

ko.bindingHandlers.test = function ($) {
    return {
        init: function (el, valueAccessor, bindingsAccessor, viewModel) {
        },
        update: function (el, valueAccessor, bindingsAccessor, viewModel) {
        }
    }
}

View:

<input type="text" data-bind="test: ???, value: 0, settings: { test: 'test-value' }">

Solution

  • your code is wrong since you have have a closure scope you need todo

    ko.bindingHandlers.test = (function ($) {
        return {
            init: function (el, valueAccessor, bindingsAccessor, viewModel) {
            },
            update: function (el, valueAccessor, bindingsAccessor, viewModel) {
            }
        }
    })(jQuery);
    

    edit: In your markup bind test to a member on your viewModel like

    <input type="text" data-bind="test: myMember />
    

    To access the binding from your custom binding

    init: function (el, valueAccessor, bindingsAccessor, viewModel) {
       var value = ko.utils.unwrapObservable(valueAccessor());
    }