PDA

View Full Version : [Prototype] Adding arguments to event handlers


scott212
12-29-2008, 06:34 PM
In the code below, why does 'index' come back as undefined when the row is clicked on? Is it being evaluated when the event is called and thus is through it's lifecycle? How should I do this?
_populateTable: function(data) {
// remove children of 'this.tbody' if exists so that data can be reloaded

data.each(function(item,index) {
var tr = new Element('tr',{'id':index});
this._tbody.appendChild(tr);

tr.observe('click', function(event,index){
alert(index);
});

this._columnModel.each(function(column) {
var td = new Element('td').update(item[column]);
tr.appendChild(td);
}.bind(this));
}.bind(this));
},

scott212
12-29-2008, 07:13 PM
I love prototype. Inside your handler function, 'this' is the element that initiated the event.

like this:
_populateTable: function(data) {
// remove children of 'this.tbody' if exists so that data can be reloaded

data.each(function(item,index) {
var tr = new Element('tr',{'id':index});
this._tbody.appendChild(tr);

tr.observe('click', function(event){
alert(this.id);
});

this._columnModel.each(function(column) {
var td = new Element('td').update(item[column]);
tr.appendChild(td);
}.bind(this));
}.bind(this));
},

Reference: http://prototypejs.org/api/event/observe