【发布时间】:2015-12-07 23:36:49
【问题描述】:
我正在尝试编写自己的事件委托系统,它工作得很好,只是一旦我将事件附加到元素上就无法删除它!我一直在扯头发试图弄清楚这一点。任何帮助将不胜感激。
代码在笔中:http://codepen.io/anon/pen/BjyZyV?editors=101
还有以下:
标记
<ul id="parent">
<li class="item">Lorum</li>
<li class="item">Lorum</li>
<li class="item">Lorum</li>
<li class="item">Lorum</li>
<li class="item">Lorum</li>
<li class="item">Lorum</li>
<li class="item">Lorum</li>
<li class="item">Lorum</li>
<li class="item">Lorum</li>
<li class="item">Lorum</li>
</ul>
Javascript
Element.prototype.matches = Element.prototype.matches || Element.prototype.msMatchesSelector;
function isDescendant(parents, child) {
for (var i = 0; i < parents.length; i++) {
var node = child.parentNode;
while (node !== null) {
if (node === parents[i]) {
return true;
}
node = node.parentNode;
}
}
return false;
}
function eventCallback(e) {
if (e.target && e.target.matches(this.options.selector)) {
this.options.callback.call(this, e);
} else if (isDescendant(this.parent.querySelectorAll(this.options.selector), e.target)) {
this.options.callback.call(this, e);
}
}
var MyEvent = {
register: function register(options) {
this.parent = document.querySelector(options.parentSelector);
this.options = options;
this.parent.addEventListener(options.event, eventCallback.bind(this), false);
return this;
},
unregister: function unregister(options) {
this.parent = document.querySelector(options.parentSelector);
this.parent.removeEventListener(options.event, eventCallback, false);
return this;
}
};
myEvent = Object.create(MyEvent);
myEvent.register({
event: 'click',
parentSelector: '#parent',
selector: '.item',
callback: function(e) {
alert('clicked!');
}
});
myEvent.unregister({
event: 'click',
parentSelector: '#parent'
});
【问题讨论】:
标签: javascript event-handling dom-events event-delegation