I'm creating multiple click events on a bunch of dynamically generated LI elements. But when I click any of them only the last li's event is dispatched.
It's a little hard to explain but here's a fiddle that will make things more clear:
...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. As a result you've got the link to the last Child
instance in _this
.
See my example: http://jsfiddle.net/5uecp/4/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.