views:

19

answers:

1

I have bulid a js class that is have the control (html Control ) parameter, i try to add dinamicly onchange event to the control but i have the folowing error:

htmlfile: Not implemented

//-------------- the code

Contrl.prototype.AddChangeEvent = function() {

    var element = this.docID;
    var fn = function onChange(element) {

     // action



    };

    if (this.tag == "input" && (this.el.type == "radio")) {
        this.el.onclick = fn(element); // there i have the error 
    }
    else {
        this.el.onchange = fn(element); // there i have the error 
    }
}
+1  A: 

By writing this.el.onclick = fn(element), you're calling fn immediately, and assigning whatever fn returns to onclick.

You need to make an anonymous function that calls fn with the arguments you want it to get, like this:

this.el.onclick = function() { return fn(element); };

However, this is not the correct way to assign event handlers in Javascript.

You should call attachEvent (for IE) or addEventListener (for everything else), like this:

function bind(elem, eventName, handler) {
    if (elem.addEventListener)
        elem.addEventListener(eventName, handler, false);
    else if (elem.attachEvent)
        elem.attachEvent("on" + eventName, handler);
    else
        throw Error("Bad browser");
}
SLaks
Not only calling but bind to this.el.onclick
@haroldis: No, you aren't binding it. You're _trying_ to bind it, but you aren't succeeding.
SLaks