I am using following code but it returns following error:
Uncaught TypeError: Object [object HTMLAnchorElement] has no method 'userInput'
Here is the code jsfiddle:
var ClickEvent = function (event) {
this.ev = $('.' + event);
this.ev.on('click', function () { this.userInput(); });
};
ClickEvent.prototype = function () {
return {
userInput: function () {
console.log('user');
},
show: function () {
console.log('show');
}
};
}();
var c = new ClickEvent('event');
I am calling userInput function inside on() callback function but it returns above error.
How can I solve this problem?
The problem is the execution context(this) inside the click callback handler does not point to the ClickEvent instance, it is referencing the dom element that was clicked.
You need to use
this.ev.on('click', $.proxy(function () { this.userInput(); }, this));
Demo: Fiddle
or
var that = this;
this.ev.on('click', function () { that.userInput(); });
Demo: Fiddle
this.userInput() is nested within the callback function, and thus is scoped within it. You could externalize the this instance you need as follow:
var ClickEvent = function (event) {
var $this = this;
$this.ev = $('.' + event);
$this.ev.on('click', function () { $this.userInput(); });
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With