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?
JavaScript
x
17
17
1
function editor () {
2
3
this.init = function () {
4
$("#area").bind('click' , this.click_event );
5
6
}
7
8
this.addElement = function () {
9
console.log("adding element");
10
}
11
12
this.click_event = function(event) {
13
this.addElement();
14
console.log("click event in x : "+event.data);
15
}
16
}
17
Advertisement
Answer
JavaScript
1
18
18
1
function editor () {
2
var that = this;
3
4
this.init = function () {
5
$("#area").bind('click' , this.click_event );
6
7
}
8
9
this.addElement = function () {
10
console.log("adding element");
11
}
12
13
this.click_event = function(event) {
14
that.addElement();
15
console.log("click event in x : "+event.data);
16
}
17
}
18
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