1

I'm having a litte problem here, I wan't to add event listener to click event. When click even happens, function gets triggered normally, but when it should call another function, it gives error:

TypeError: this.addEvent is not a function

Code:

class TEST {
    construct(){
        this.events = [];
    }
}

TEST.prototype.ready = function(callback) {
    if (document.readyState!='loading') callback();
    else if (document.addEventListener) document.addEventListener('DOMContentLoaded', callback);
    else document.attachEvent('onreadystatechange', function(){
        if (document.readyState=='complete') callback();
    });
}

TEST.prototype.addEvent = function (event) {
    this.events.push(event);
}

TEST.prototype.clickEvent = function (e) {
    var pos = {
        x: e.pageX,
        y: e.pageY
    };

    var event = {
        type: 'click',
        data: pos,
        timestamp: new Date()
    };

    this.addEvent(event);
}

TEST.prototype.init = function () {
    document.addEventListener('click', this.clickEvent);
}

var test = new TEST();
test.ready(function(){
    test.init();
});

JSFiddle:
https://jsfiddle.net/x2hLw009/

Any help appreciated, thanks!

EDIT

I added bind to addEventListener:

document.addEventListener('click', this.clickEvent.bind(this));

But when function continues to this.addEvent(), I get new error:

TypeError: this.events is undefined

On this line:

this.events.push(event);
Lanibox
  • 43
  • 9

1 Answers1

4

The reason it's breaking is because of this scoping. The "this" inside of your clickEvent function is relative to whatever is calling it.

So, since the document is calling it, "this" would probably refer to the document. If you want to force it to refer to the current object, you'll use the bind prototype.

document.addEventListener('click', this.clickEvent.bind(this));