user6669
user6669

Reputation: 155

Event never firing?

I am trying to add some event listener to document, but for some reason it looks like the click event is never fired, because the callback is never called:

function NotJquery(element) {
    this.element = element;

    return this;
}

NotJquery.prototype.eventFired = function(event, callback) {
    console.log('in NotJquery prototype');
    return function (event, callback) {
        element.addEventListener(event, callback, true);
    };
};
    
var $ = function(element) {
    return new NotJquery(element);
};

function Test() {
}
    
Test.prototype.addListener = function() {
    console.log('in Test prototype');
    $(document).eventFired('click', function() {
        console.log('click event fired');
    });
};

(function() {
    var test= new Test();
    test.addListener();
}());

Both the messages: "in Test prototype" and "in NotJquery prototype" are logged in the console, but when I click somewhere in my document the message "click event fired" is not output in the console. I do not see what is wrong with my code. Anybody has an idea to get it working?

http://jsfiddle.net/Nn3tZ/1/

Upvotes: 0

Views: 82

Answers (2)

Esailija
Esailija

Reputation: 140236

Your client code is expecting something like this:

NotJquery.prototype.eventFired = function(event, callback) {
    this.element.addEventListener(event, callback, false);
};

Working demo: http://jsfiddle.net/Nn3tZ/2/

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075587

element is not defined within your eventFired function (but that's not the only problem). Here's a minimal update:

NotJquery.prototype.eventFired = function(event, callback) {
    var self = this; // <== Change 1 of 2

    console.log('in NotJquery prototype');
    return function () {
        self.element.addEventListener(event, callback, true);
    //  ^-- Change 2 of 2
    };
};

Unlike some other languages (Java, C#), this is not optional when referring to a property on the current object. Separately, the function you're creating within eventFired won't have the right this, so that's why I've stowed it away as self and then used self within the generated function (which is a closure).

Separately, you're passing event and callback into eventFired but then also declaring them on the generated function (it's not at all clear to me why you're generating a function there at all), so the ones you pass into eventFired are never used.

More reading (on my anemic blog):

Upvotes: 1

Related Questions