我需要一种方法让Knockout中的所有模板绑定相同的事件函数,例如:
ko.bindingHandlers.foreach.afterAdd = function(){ ... }
答案 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);
}
};