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);
}
}
Advertisement
Answer
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