Question

I need a way to make all templates in Knockout bind the same event functions, something like:

ko.bindingHandlers.foreach.afterAdd = function(){ ... }
Was it helpful?

Solution

You could write a wrapper to the template binding that adds those options in a foreach scenario. Perhaps something like:

ko.bindingHandlers.myTemplate = {
    init: function (element, valueAccessor, allBindings, value, context) {
        var options = ko.unwrap(valueAccessor());

        if (options && typeof options === "object" && options.foreach) {
            options.afterAdd = ko.bindingHandlers.myTemplate.afterAdd;
            options.beforeRemove = ko.bindingHandlers.myTemplate.beforeRemove;
        } 

        ko.applyBindingsToNode(element, {
            template: options
        }, context);


        return {
            controlsDescendantBindings: true
        };
    },
    beforeRemove: function (element, data) {
        console.log("remove", element, data);

        ko.removeNode(element);
    },
    afterAdd: function (element, data) {
        console.log("add", element, data);
    }
};

Sample: http://jsfiddle.net/rniemeyer/Xnbe2/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top