[英]Multiple listeners created but only the last responding
I'm creating multiple click events on a bunch of dynamically generated LI elements. 我正在一堆动态生成的LI元素上创建多个click事件。 But when I click any of them only the last li's event is dispatched.
但是当我点击其中任何一个时,只会调度最后一个li的事件。
It's a little hard to explain but here's a fiddle that will make things more clear: 这有点难以解释,但这里有一个小提琴,可以让事情变得更加清晰:
http://jsfiddle.net/5uecp/2/ http://jsfiddle.net/5uecp/2/
...and the code: ......和代码:
// Parent Class
function Parent(id, children) {
this.id = id;
this.children = children;
this.init();
}
Parent.prototype = {
init: function () {
this.addEventHanlders()
},
addEventHanlders: function () {
addEventListener('childEvent', function (e) {
e.stopPropagation()
// console.log('childEvent', e.title)
});
},
render: function () {
var ul = document.createElement('ul');
ul.setAttribute('id', this.id)
for (var i = this.children.length - 1; i >= 0; i--) {
ul.appendChild(this.children[i].render());
};
document.body.appendChild(ul);
}
}
// Child Class
function Child(title) {
this.title = title;
this.li = null
this.event = document.createEvent("Event");
};
Child.prototype = {
render: function () {
_this = this;
this.li = document.createElement('li');
text = document.createTextNode(this.title);
a = document.createElement('a');
a.setAttribute('href', '#');
a.appendChild(text);
this.li.appendChild(a);
this.li.setAttribute('class', 'child');
this.li.addEventListener('click', this.clickEventHandler, true);
return this.li;
},
clickEventHandler: function (e) {
e.preventDefault();
_this.changeColor();
_this.fireEvent();
e.target.removeEventListener('click', this.clickEventHandler)
},
changeColor: function (color) {
color = color || 'red';
this.li.style.backgroundColor = color;
},
fireEvent: function () {
console.log('fireEvent', this.title);
this.event.initEvent("childEvent", true, true);
this.event.title = this.title;
document.dispatchEvent(this.event);
}
};
// Initialize
children = [new Child("Child 1"), new Child("Child 2"), new Child("Child 3"), new Child("Child 4"), new Child("Child 5")]
parent = new Parent("parent", children)
$(function () {
parent.render();
});
The problem is that you are saving this
into the global variable _this
, that is accessible from everywhere. 问题是,您要保存
this
为全局变量_this
,这是来自世界各地的访问。 As a result you've got the link to the last Child
instance in _this
. 结果你得到了
_this
最后一个Child
实例的_this
。
See my example: http://jsfiddle.net/5uecp/4/ 看看我的例子: http : //jsfiddle.net/5uecp/4/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.