I am having trouble with how to addEventLisener
to an object when writing a member function for that object.
在编写该对象的成员函数时,我遇到了如何将addEventLisener添加到对象的问题。
I have a class called Grid
which has a member function create
that creates a HTML div
element. Now I want to add an event listener to that div
, which waits for click
. Here is the code.
我有一个名为Grid的类,它有一个成员函数create,用于创建一个HTML div元素。现在我想为该div添加一个事件监听器,等待点击。这是代码。
Notice that I have another member function update
for the Grid.
请注意,我有另一个Grid的成员函数更新。
Grid.prototype.create = function(index) {
var newnode = document.createElement("div");
newnode.setAttribute("class", "grid");
newnode.setAttribute("id", "grid" + index);
newnode.style.width = this.width + "px";
newnode.style.height = this.height + "px";
document.getElementById("whole").appendChild(newnode);
newnode.addEventListener("click", function() {
if (this.live) {
this.live = false;
} else {
this.live = true;
}
this.update(index);
}, false);
this.update(index);
};
The problem is, this
represents an HTML DIV Object
inside the addEventListener
block , but I need it to be a Grid Object
so that the update
function can be called.
问题是,这表示addEventListener块中的HTML DIV对象,但我需要它是一个Grid对象,以便可以调用更新函数。
How to solve this problem? Or is there another way to add listener for an object whenever the div
that contains it is created?
如何解决这个问题呢?或者,只要创建包含它的div,就有另一种方法为对象添加侦听器吗?
1 个解决方案
#1
1
Just use a variable that is declared outside the scope of the event handler
只需使用在事件处理程序范围之外声明的变量
Grid.prototype.create = function(index) {
var grid = this,
newnode = document.createElement("div");
newnode.className = "grid";
newnode.id = "grid" + index;
newnode.style.width = this.width + "px";
newnode.style.height = this.height + "px";
newnode.addEventListener("click", function() {
grid.live = !grid.live;
grid.update(index);
}, false);
document.getElementById("whole").appendChild(newnode);
this.update(index);
};
#1
1
Just use a variable that is declared outside the scope of the event handler
只需使用在事件处理程序范围之外声明的变量
Grid.prototype.create = function(index) {
var grid = this,
newnode = document.createElement("div");
newnode.className = "grid";
newnode.id = "grid" + index;
newnode.style.width = this.width + "px";
newnode.style.height = this.height + "px";
newnode.addEventListener("click", function() {
grid.live = !grid.live;
grid.update(index);
}, false);
document.getElementById("whole").appendChild(newnode);
this.update(index);
};