문제

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

ko.bindingHandlers.foreach.afterAdd = function(){ ... }
도움이 되었습니까?

해결책

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/

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top