Skip to content
mbest edited this page Dec 9, 2011 · 3 revisions

Here's a custom binding that allows you run a function after an element is updated. It takes advantage of the fact that the update functions for all bindings are called whenever any of the dependencies are updated.

ko.bindingHandlers['runafter'] = {
    'update': function(element, valueAccessor, allBindingsAccessor) {
        setTimeout(function() {
            var value = valueAccessor();
            if (typeof value != 'function' || ko.isObservable(value))
                throw new Error('run must be used with a function');
            value(element);
        }, 0);
    }
};

Here's a fiddle showing it working and also showing that it doesn't work if you use it with the template binding (because templates are updated by a separate process).

I've been working on an update to Knockout that doesn't call each update function every time. This change breaks the functionality of the runafter binding. So here's runafter changed to work with that version of Knockout.

ko.bindingHandlers['runafter'] = {
    'update': function(element, valueAccessor, allBindingsAccessor) {
        // make a subscription to all values and make sure all other bindings are run first
        var allBindings = allBindingsAccessor();
        for (bindingKey in allBindings) {
            if (bindingKey != 'runafter')
                allBindingsAccessor(bindingKey);
        }
        var value = valueAccessor();
        if (typeof value != 'function' || ko.isObservable(value))
            throw new Error('run must be used with a function');
        value(element);
    }
};
Clone this wiki locally