views:

32

answers:

1

I have this code i am working on but every time i call init method I keep getting an error

this.addElement is not a function

is it because i can't call methods from event handlers ?

function editor () {

    this.init = function () {
        $("#area").bind('click' , this.click_event );

    }

    this.addElement = function () {
        console.log("adding element");
    }

    this.click_event = function(event) {
        this.addElement();
        console.log("click event in x : "+event.data);
    }
}
+3  A: 
function editor () {
    var that = this;

    this.init = function () {
        $("#area").bind('click' , this.click_event );

    }

    this.addElement = function () {
        console.log("adding element");
    }

    this.click_event = function(event) {
        that.addElement();
        console.log("click event in x : "+event.data);
    }
}

You should read this book, JavaScript: the Good Parts and visit the Crockenator's web site here, crockford.com

You can also read about the JavaScript "this" issue here, http://www.quirksmode.org/js/this.html

nickyt
@Ayoub: Basically, `this` is very different in JavaScript than it is in some other languages, like Java or C#. It's determined entirely by how a function is *called*, not where it's defined. More: http://blog.niftysnippets.org/2008/04/you-must-remember-this.html
T.J. Crowder