我现在正在开发/已经开发了一些系统,我在编程中遇到了一个问题,我似乎将所有我的 JQuery 函数委托(delegate)给文档,如下所示:
$(document).on('click', '.modal-editor', function () {
//code
});
$(document).on('click', '.another-class', function () {
//code
});
$(document).on('click', '#another-id', function () {
//code
});
这有什么问题吗?
更新:
好吧,本质上这没有什么问题,直到:
应用程序达到一定规模,授权需要更加本地化,以防止 UI 变慢。 “发生的每个事件都需要针对 e.target 和文档之间的每个元素运行每个选择器”
如果使用嵌套函数,这样的委托(delegate)会增加出现意外行为(例如传播)的可能性。
回到我的问题(最佳实践),最佳实践是将事件委托(delegate)给尽可能最近的静态元素,以避免上述情况。
最佳答案
"Is there anything wrong with this?"
是的。发生的每个事件都需要针对 e.target
和 document
之间的每个元素运行每个选择器。这太贵了。
基本上就像这个简化的伪代码:
// start on the e.target
var node = e.target;
// For the target and all its ancestors until the bound element...
while (node && node !== this) {
// ...test the current node against every click selector it was given
for (var i = 0; i < click_selectors.length; i++) {
// If a selector matches...
if ($(node).is(selector)) {
// ...run the handler for that selector
}
}
node = node.parentNode;
}
此外,如果您的代码或加载的其他代码在 e.target
和 document
之间绑定(bind)了处理程序,并调用 e.stopPropagation()
,该事件永远不会到达文档
,因此您的事件不会触发。
最好让您的授权尽可能接近预期元素。它主要用于动态加载的元素,因为它会增加额外的开销,特别是在事件快速触发的情况下。
关于Javascript 委托(delegate)最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20706930/