プロトタイプを使用して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
'render'では、イベントリスナーをアタッチする直前です。元の例の 'addEventListener'行をこのスニペットで置き換えることができます。 – kangax
あなたがきれいに言及するのは興味深いことです。実際には、これらのオブジェクトをプロセスのある時点で破棄しています。もともと私はちょうど.innerHTML = "";私の推測は、この文脈では悪いことです。どのようにこのテーブルを破壊し、前述の漏れを避けるでしょうか? – Darthg8r