Skip to content

Implement own KnockoutJS bindings

Rico Suter edited this page Jul 24, 2015 · 7 revisions

There are a lot of custom bindings in the internet to use with KnockoutJS. Sometimes they do not work because their init() method is called before the associated HTML code has been added to the DOM. This is because the VistoJS framework initializes everything hidden to avoid GUI flickering.

An example with this problem is a custom binding which creates a jQuery accordion in the init() method. The original code might look like this:

ko.bindingHandlers.myCustomBinding = {
    init: function (element, valueAccessor) {
        // TODO: Add your code to initialize the widget here
    }
};

To run some code after the HTML is added to the DOM, it is possible to register a callback method. This method is called when the view has been added to the DOM:

ko.bindingHandlers.myCustomBinding = {
    init: function (element, valueAccessor) {
        // TODO: This code is called before the element is added to the DOM
        
        visto.addInitializer(function () {
            // TODO: This code is called after the element has been added to the DOM
        });
    }
};

Important: Use the addInitializer() method only in the KnockoutJS binding's init() method.