Search code examples
javascriptdom-events

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/


Solution

  • 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/