使所有模板foreach绑定相同的afterAdd和beforeRemove事件函数

时间:2013-09-13 14:42:49

标签: knockout.js knockout-2.0 event-binding

我需要一种方法让Knockout中的所有模板绑定相同的事件函数,例如:

ko.bindingHandlers.foreach.afterAdd = function(){ ... }

1 个答案:

答案 0 :(得分:3)

您可以为模板绑定编写一个包装器,在foreach方案中添加这些选项。也许是这样的事情:

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);
    }
};

示例:http://jsfiddle.net/rniemeyer/Xnbe2/