我通過原型創建了一個JavaScript對象。我試圖動態呈現表格。雖然渲染部分很簡單並且工作正常,但我還需要處理動態渲染表的某些客戶端事件。那也很簡單。我遇到的問題是處理事件的函數內部的「this」引用。而不是「this」引用對象,它引用引發事件的元素。使用addEventListener處理程序中的「this」的值
查看代碼。有問題的區域是「ticketTable.prototype.handleCellClick =功能()」
function ticketTable(ticks)
{
// tickets is an array
this.tickets = ticks;
}
ticketTable.prototype.render = function(element)
{
var tbl = document.createElement("table");
for (var i = 0; i < this.tickets.length; i++)
{
// create row and cells
var row = document.createElement("tr");
var cell1 = document.createElement("td");
var cell2 = document.createElement("td");
// add text to the cells
cell1.appendChild(document.createTextNode(i));
cell2.appendChild(document.createTextNode(this.tickets[i]));
// handle clicks to the first cell.
// FYI, this only works in FF, need a little more code for IE
cell1.addEventListener("click", this.handleCellClick, false);
// add cells to row
row.appendChild(cell1);
row.appendChild(cell2);
// add row to table
tbl.appendChild(row);
}
// Add table to the page
element.appendChild(tbl);
}
ticketTable.prototype.handleCellClick = function()
{
// PROBLEM!!! in the context of this function,
// when used to handle an event,
// "this" is the element that triggered the event.
// this works fine
alert(this.innerHTML);
// this does not. I can't seem to figure out the syntax to access the array in the object.
alert(this.tickets.length);
}
var _this = this;在我的代碼的上下文去? 我需要將onClickBound(e)添加到原型嗎? – Darthg8r 2009-08-27 03:05:49
在'render'中,在附加事件監聽器之前。你幾乎可以用這個代碼片段替換原始示例中的addEventListener行。 – kangax 2009-08-27 03:28:35
有趣的是,你提到清理。我實際上也會在這個過程中的某個時刻銷燬這些對象。我原本打算做.innerHTML =「」;我的猜測是在這方面不好。我將如何銷燬這些表格並避免上述泄漏? – Darthg8r 2009-08-27 11:29:59