1

I'm struggling with managing dynamically built event handlers in javascript.

In several places, I build forms, or controls in which specific events (mainly mouseovers, mouse-outs, clicks) need to be handled.

The trick is that in a significant number of cases, the event handler itself needs to incorporate data that is either generated by, or is passed-into the function that is building the form or control.

As such, I've been using "eval()" to construct the events and incorporate the appropriate data, and this has worked somewhat well.

The problem is I keep seeing/hearing things like "You should never use eval()!" as well as a couple of increasingly ugly implementations where my dynamically-built event handler needs to dynamically build other event handlers and the nested evals are pretty obtuse (to put it mildly).

So I'm here, asking if someone can please show me the better way (native javascript only please, I'm not implementing any third-party libraries!).

Here's a crude example to illustrate what I'm talking about:

function CreateInput(controlName,type,activeStyle,dormantStyle,whenClicked)
{
    var inp = document.createElement('input');
    inp.id = controlName;
    inp.type = type;
    inp.style.cssText = dormantStyle;
    eval("inp.onfocus = function() { this.style.cssText = '" + activeStyle + "'; }");
    eval("inp.onblur = function() { this.style.cssText = '" + dormantStyle + "'; }");
    eval("inp.onclick = function() { " + whenClicked + "; }");
    return inp;
}

This function obviously would let me easily create lots of different INPUT tags and specify a number of unique attributes and event actions, with just a single function call for each. Again, this is an extremely simplified example, just to demonstrate what I'm talking about, in some cases with the project I'm on currently, the events can incorporate dozens of lines, they might even make dynamic ajax calls based on a passed parameter or other dynamically generated data. In more extreme cases I construct tables, whose individual rows/columns/cells may need to process events based on the dynamically generated contents of the handler, or the handler's handler.

Initially, I had built functions like the above as so:

function CreateInput(controlName,type,activeStyle,dormantStyle,whenClicked)
{
    var inp = document.createElement('input');
    inp.id = controlName;
    inp.type = type;
    inp.style.cssText = dormantStyle;
    inp.onfocus = function() { this.style.cssText = activeStyle; };
    inp.onblur = function() { this.style.cssText = dormantStyle; };
    eval("inp.onclick = function() { " + whenClicked + "; }");
    return inp;
}

...but I found that whatever the last assigned value had been for "activeStyle", and "dormantStyle" became the value used by all of the handlers thusly created (instead of each retaining its own unique set of styles, for example). That is what lead me to using eval() to "lock-in" the values of the variables when the function was created, but this has lead me into nightmares such as the following:

(This is a sample of one dynamically-built event-handler that I'm currently working on and which uses a nested eval() function):

    eval("input.onkeyup = function() { " +
            "InputParse(this,'ucwords'); " +
            "var tId = '" + myName + This.nodeName + "SearchTable" + uidNo + "'; " +
            "var table = document.getElementById(tId); " +
            "if (this.value.length>2) { " +
                "var val = (this.value.indexOf(',') >=0 ) ? this.value.substr(0,this.value.indexOf(',')) : this.value; " +
                "var search = Global.LoadData('?fn=citySearch&limit=3&value=' + encodeURI(val)); " +
                "if (table) { " +
                    "while (table.rows.length>0) { table.deleteRow(0); } " +
                    "table.style.display='block'; " +
                "} else { " +
                    "table = document.createElement('table'); " +
                    "table.id = tId; " +
                    "ApplyStyleString('" + baseStyle + ";position=absolute;top=20px;left=0px;display=block;border=1px solid black;backgroundColor=rgba(224,224,224,0.90);zIndex=1000;',table); " +
                    "var div = document.getElementById('" + divName + "'); " +
                    "if (div) { div.appendChild(table); } " +
                "} " +
                "if (search.rowCount()>0) { " +
                    "for (var i=0; i<search.rowCount(); i++) { " +
                        "var tr = document.createElement('tr'); " +
                        "tr.id = 'SearchRow' + i + '" + uidNo + "'; " +
                        "tr.onmouseover = function() { ApplyStyleString('cursor=pointer;color=yellow;backgroundColor=rgba(40,40,40,0.90);',this); }; " +
                        "tr.onmouseout = function() { ApplyStyleString('cursor=default;color=black;backgroundColor=rgba(224,224,224,0.90);',this); }; " +
                        "eval(\"tr.onclick = function() { " +
                            "function set(id,value) { " +
                                "var o = document.getElementById(id); " +
                                "if (o && o.value) { o.value = value; } else { alert('Could not find ' + id); } " +
                            "} " +
                            "set('" + myName + This.nodeName + "CityId" + uidNo + "','\" + search.id(i)+ \"'); " +
                            "set('" + myName + This.nodeName + "ProvId" + uidNo + "','\" + search.provId(i)+ \"'); " +
                            "set('" + myName + This.nodeName + "CountryId" + uidNo + "','\" + search.countryId(i) + \"'); " +
                            "set('" + input.id + "','\" + search.name(i)+ \"'); " +
                            "}\"); " +
                        "var td = document.createElement('td'); " +
                        "var re = new RegExp('('+val+')', 'gi'); " +
                        "td.innerHTML = search.name(i).replace(re,'<span style=\"font-weight:bold;\">$1</span>') + ', ' + search.provinceName(i) + ', ' + search.countryName(i); " +
                        "tr.appendChild(td); " +
                        "table.appendChild(tr); " +
                    "} " +
                "} else { " +
                    "var tr = document.createElement('tr'); " +
                    "var td = document.createElement('td'); " +
                    "td.innerHTML = 'No matches found...';" +
                    "tr.appendChild(td); " +
                    "table.appendChild(tr); " +
                "} " +
            "} else { " +
                "if (table) table.style.display = 'none'; " +
            "} " +
        "} ");

Currently, I'm having problems getting the nested eval() to bind the ".onclick" event to the table-row, and, as you can see, figuring out the code is getting pretty hairy (debugging too, for all the known reasons)... So, I'd really appreciate it if someone could point me in the direction of being able to accomplish these same goals while avoiding the dreaded use of the "eval()" statement!

Thanks!

NetXpert
  • 511
  • 5
  • 14
  • This screams for something like jQuery, but since you don't want to use third party libs: your initial solution (with only one `eval`) makes much more sense. That `activeStyle` and `dormantStyle` 'stick' has probably to do with the context from where you call `createInput` (in a `for` loop perhaps?) and not that function itself. – robertklep Feb 11 '13 at 07:09

2 Answers2

1

And this, among many other reasons, is why you should never use eval. (What if those values you're "baking" in contain quotes? Oops.) And more generally, try to figure out why the right way doesn't work instead of beating the wrong way into submission. :)

Also, it's not a good idea to assign to on* attributes; they don't scale particularly well. The new hotness is to use element.addEventListener, which allows multiple handlers for the same event. (For older IE, you need attachEvent. This kind of IE nonsense is the primary reason we started using libraries like jQuery in the first place.)


The code you pasted, which uses closures, should work just fine. The part you didn't include is that you must have been doing this in a loop.

JavaScript variables are function-scoped, not block-scoped, so when you do this:

var callbacks = [];
for (var i = 0; i < 10; i++) {
    callbacks.push(function() { alert(i) });
}

for (var index in callbacks) {
    callbacks[index]();
}

...you'll get 9 ten times. Each run of the loop creates a function that closes over the same variable i, and then on the next iteration, the value of i changes.

What you want is a factory function: either inline or independently.

for (var i = 0; i < 10; i++) {
    (function(i) {
        callbacks.push(function() { alert(i) });
    })(i);
}

This creates a separate function and executes it immediately. The i inside the function is a different variable each time (because it's scoped to the function), so this effectively captures the value of the outer i and ignores any further changes to it.

You can break this out explicitly:

function make_function(i) {
    return function() { alert(i) };
}

// ...

for (var i = 0; i < 10; i++) {
    callbacks.push(make_function(i));
}

Exactly the same thing, but with the function defined independently rather than inline.

This has come up before, but it's a little tricky to spot what's causing the surprise.


Even your "right way" code still uses strings for the contents of functions or styles. I would pass that click behavior as a function, and I would use classes instead of embedding chunks of CSS in my JavaScript. (I doubt I'd add an ID to every single input, either.)

So I'd write something like this:

function create_input(id, type, active_class, onclick) {
    var inp = document.createElement('input');
    inp.id = id;
    inp.type = type;
    inp.addEventListener('focus', function() {
        this.className = active_class;
    });
    inp.addEventListener('blur', function() {
        this.className = '';
    });
    inp.addEventListener('click', onclick);

    return inp;
}

// Called as:
var textbox = create_input('unique-id', 'text', 'focused', function() { alert("hi!") });

This has some problems still: it doesn't work in older IE, and it will remove any class names you try to add later. Which is why jQuery is popular:

function create_input(id, type, active_class, onclick) {
    var inp = $('<input>', { id: id, type: type });
    inp.on('focus', function() {
        $(this).addClass(active_class);
    });
    inp.on('blur', function() {
        $(this).removeClass(active_class);
    });

    inp.on('click', onclick);

    return inp;
}

Of course, even most of this is unnecessary—you can just use the :focus CSS selector, and not bother with focus and blur events at all!

Community
  • 1
  • 1
Eevee
  • 47,412
  • 11
  • 95
  • 127
  • As I said, that was just a _very_ simplified example. The last-posted code-sample is much more like what I'm dealing with (although it's only a fraction of the entire function). – NetXpert Feb 11 '13 at 07:36
  • I much prefer defining my styles WHERE I USE them, over having to refer back to a separate document, which could ultimately end-up containing thousands of entries. When an element in my application doesn't look correct, I just go to the code where that element is built and adjust it. With a CSS file, I'd have to go the the code, find the class reference, go to the css file, then look-up the class, then make the change. This way produces the same result but shortens the number of steps. Plus I don't have any issues around coming up with names for thousands of classes (collisions, typos etc). – NetXpert Feb 11 '13 at 07:47
  • if you were inspecting your document in a browser with a debugger, you could very easily see what classes an element had, so finding the appropriate CSS is easy. but there's no easy way to figure out what JS originally _created_ the element, unless you already happen to remember. – Eevee Feb 11 '13 at 18:14
  • I've written 99% of my code (the benefit of not touching libraries), so remembering what I wrote isn't that difficult. Classes (CSS I mean) annoy me because the idea of having, everytime I create an element, to create another, new, unique, descriptive class name, then go to another file and write the class, before coming back and continuing on is a lot of extra overhead, compared to simply defining the characteristics of the element, and applying them to it at the time when the element is instantiated. – NetXpert Feb 11 '13 at 23:45
  • So now I'm struggling trying to comprehend javascript "Closure" (a term/concept I've never encountered before). Unfortunately, the hyper-simplification of my example, and the concentration on it in your answers, really hasn't made anything clearer. For example, I reference "this" quite often when crafting event handlers, but with the examples above, I don't know what scope "this" will refer to when I use it. I'm also not really understanding how you're implementing closure above. My experience with nested functions and variable-scope comes from Pascal, and I was treating these in the same way. – NetXpert Feb 12 '13 at 00:10
0

You don't need eval to "lock in" a value.

It's not clear from the posted code why you're seeing the values change after CreateInput returns. If CreateInput implemented a loop, then I would expect the last values assigned to activeStyle and dormantStyle to be used. But even calling CreateInput from a loop will not cause the misbehavior you describe, contrary to the commenter.

Anyway, the solution to this kind of stale data is to use a closure. JavaScript local variables are all bound to the function call scope, no matter if they're declared deep inside the function or in a loop. So you add a function call to force new variables to be created.

function CreateInput(controlName,type,activeStyle,dormantStyle,whenClicked)
{
    while ( something ) {
        activeStyle += "blah"; // modify local vars
        function ( activeStyle, dormantStyle ) { // make copies of local vars
            var inp = document.createElement('input');
            inp.id = controlName;
            inp.type = type;
            inp.style.cssText = dormantStyle;
            inp.onfocus = function() { this.style.cssText = activeStyle; };
            inp.onblur = function() { this.style.cssText = dormantStyle; };
            inp.onclick = whenClicked;
        }( activeStyle, dormantStyle ); // specify values for copies
    }
    return inp;
}
Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
  • Hmm, well I see the new code that you've put in, but you've also retained the eval() statements, is that correct? and if so, what's the benefit to adding the extra code then? – NetXpert Feb 11 '13 at 07:25
  • @BrettLeuszler Sorry, I meant to erase them. fixed. – Potatoswatter Feb 11 '13 at 07:26