1

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

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

1 回答 1

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/

于 2013-09-13T15:23:20.517 回答