2

I'm putting together a JavaScript object called ListBox which takes a two-dimensional array, and outputs it in a table with fixed column titles, scrollable content, and is sortable by clicking a column title. In order for the HTML to include event handlers which call the object's own methods, the object needs to know its own instance variable name, eg....

var MyList = new ListBox();

After setting up the columns & contents the appropriate method will generate the HTML...

...
<td class="ListBox_ColumnTitle" onclick="MyList.SortByColumn(1)">...</td>
...

By searching here on stackoverflow I found the following code, and adapted it slightly so it finds the right instance of the object:

for (var v in window) {
    try {
        if (window[v] instanceof ListBox) { InstanceName = v; break; }
        }
    catch (e) { }
    }

However this doesn't work inside the constructor function - it simply doesn't find the instance. It works fine afterwards, but I'd like to be able to do it within the constructor to make the code which is using ListBox simpler - is this possible?

Also I do realise it would be much simpler to just pass the variable name as a parameter of the constructor, but I'd like to avoid this if I can.

Niko
  • 26,516
  • 9
  • 93
  • 110
Iain
  • 307
  • 4
  • 17

2 Answers2

2

You can avoid this problem completely by binding the events in script and not outputing onclick attributes.

function ListBox() {
    var that = this;

    // do your existing stuff

    var element = ...; // whatever you're currently doing to create the html
    element.onclick = function () {
        that.SortByColumn(1);
    };
}
bhamlin
  • 5,177
  • 1
  • 22
  • 17
  • Why do you need the 'var that = this'? Won't it work using 'this' when setting the onclick function? – Iain Jun 27 '12 at 19:35
  • @Iain No, inside the onclick function `this` would refer to the element being clicked. That's why we need `that` to refer to the `ListBox` object. – bhamlin Jun 27 '12 at 20:02
0

Don't do it. Never try to get the name of a variable.

Instead, you should use objects and references to them. You should not generate HTML (strings), but DOM elements (objects). You can easily assign functions to them as event listeners to which only you have access in your scope.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375