Ho creato un oggetto javascript tramite la prototipazione. Sto cercando di rendere una tabella dinamicamente. Mentre la parte di rendering è semplice e funziona bene, devo anche gestire alcuni eventi lato client per la tabella resa dinamicamente. Anche questo è facile. Dove sto avendo problemi è con il "questo" riferimento all'interno della funzione che gestisce l'evento. Invece di "questo" fa riferimento all'oggetto, fa riferimento all'elemento che ha generato l'evento.Il valore di "this" nel gestore utilizzando addEventListener
Vedere codice. L'area problematica è in "ticketTable.prototype.handleCellClick = function()"
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);
}
Dove var = questo = questo; nel contesto del mio codice vai? Devo aggiungere onClickBound (e) al prototipo? – Darthg8r
In 'render', subito prima di collegare il listener di eventi. Puoi praticamente sostituire la riga 'addEventListener' dall'esempio originale con questo snippet. – kangax
È interessante che tu menzioni la pulizia. In effetti, distruggerò questi oggetti anche a un certo punto del processo. Inizialmente avevo programmato di fare .innerHTML = ""; La mia ipotesi è che sia male in questo contesto. Come distruggerei questi tavoli ed evitare la perdita menzionata? – Darthg8r