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);
}
}
2 Answers 2
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
1 Comment
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: blog.niftysnippets.org/2008/04/you-must-remember-this.html Fast forward 12 years and we now have arrow functions :-)
I faced something similar and wrote up how I solved it with an arrow function.
Though it's on salesforce.stackexchange.com, it's about this in core Javascript:
this, insideclick_event? Understand that, and the world is your shellfish.this, it is still there implicitly:this.addElement()is the same asaddElement(). But inspectthis- it is quite likely it's not what you wanted.thisdoesn't point to the object ofeditoranymore. Do aconsole.log(this)insideaddElementto find out whatthisis referring to.