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.

1
  • 3
    The real problem is a bad design. Code should know nothing about calling code. That's the calling code's job. Commented Jun 27, 2012 at 18:46

2 Answers 2

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);
    };
}
Sign up to request clarification or add additional context in comments.

2 Comments

Why do you need the 'var that = this'? Won't it work using 'this' when setting the onclick function?
@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.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.