views:

1404

answers:

1

I have created a project in Dashcode, inserted a List control, enabled a dynamic list, created a JSON object and associated it with the control. The code looks like this ...

var stations = {

    _rowData: ["Mitchelton", "Gaythorne", "Albion", "Central", 
    "Burpengary", "Petrie", "Morayfield", "Caboolture", "Ferny Grove"],

    numberOfRows: function() { return this._rowData.length; },

    prepareRow: function(rowElement, rowIndex, templateElements) {
        if (templateElements.label) {
            templateElements.label.innerText = this._rowData[rowIndex];
        }
        rowElement.onclick = function(event) { alert("Row "+rowIndex); };
    }

As you can see when an item is selected it will print the rowIndex, but I would like to display the actual value at that index.

Unfortunately this (for example) "this._rowData[2]" doesnt work, it doesn't seem to be able to find the "_rowData" object.

+2  A: 

This should work:

prepareRow: function(rowElement, rowIndex, templateElements) {
    if (templateElements.label) {
     templateElements.label.innerText = this._rowData[rowIndex];
    }

    var _this = this;
    rowElement.onclick = function(event) { alert(_this._rowData[2]); };
}

The problem is that within the rowElement.onclick event handler, this refers to the DOM element rowElement, not your stations object. We fix the problem by creating a variable (I've named it _this, but you can call it whatever you want) that points to the stations object and then using this variable whenever we want to access the stations object inside the event handler.

See the following two articles for more information on the this keyword:

Steve Harrison
sweet, thanks a bunch :) This kinda explains some code I saw earlier (while googling for an answer for this problem) where someone had put "var self = this" ... I thought they had gone nuts or something, but now I see what they were doing :)
Nippysaurus
Yes! If you look at the AppleClasses, you'll notice they also create a variable "self" in situations like this...
Steve Harrison