0

I am working on javascript project. In this I have to use JavaScript and jQuery no JavaScript / jQuery Libraries such as Backbone. Therefore, I am following prototype javascript. In this I have to listen to user events and take actions accordingly. I am currently handling these events like following

var Module = function (el) {
    var self = this;
    // I am handling click events in constructor here
    $('.' + el).on('click', function (e) { e.preventDefault(); self.foo() })
};

Module.prototype = function () {
    var foo = function () {
         console.log();
    };

    return {
        foo: foo
    }
}();

It works fine. Second way is to listen these events inside $(function () { });. However, this way it becomes messy at some point. My question is how can I make my own events object so that it listen these events and call appropriate function or module?

Om3ga
  • 30,465
  • 43
  • 141
  • 221
  • What does "JavaScript and jQuery no JavaScript / jQuery Libraries" mean? – Ringo Aug 17 '13 at 10:10
  • 1
    Have you tried creating your own event with `createEvent()` and rising them with `dispatchEvent()`? See [JavaScript custom Event Listener](http://stackoverflow.com/a/10085161/1080090). In addition, if you are using backbone take a look at [Using backbone custom events and the observer pattern](https://gist.github.com/davemo/1270297). – phemios Aug 17 '13 at 10:15
  • @Ringo read it it says such as Backbone. I will add more here. Such as Angular, Knockoff etc etc – Om3ga Aug 17 '13 at 10:17
  • The link phemios linked was really god for understanding an event system. I would also like to recommend this [building a minima javascript event system](http://blog.joecorcoran.co.uk/2013/06/01/building-a-minimal-javascript-event-system/) for a really god look into different ways of implementing such a system, the writer also develops it in a test driven way so it's a good post for everyone starting out with TDD. – Trond Hatlen Aug 17 '13 at 10:25
  • @TrondHatlen the link you provided says `404 Not Found` – Om3ga Aug 17 '13 at 10:27

1 Answers1

0

May it's this what your looking for:

function Module(element, type, useCapture){

    // you can register more than one handler for a certain event of an element
    element.addEventListener(type, this.eventHandlers[type], useCapture);
    // or register only one handler for a certain event of an element
    element['on'+type] = this.eventHandlers[type];

}

Module.prototype.eventHandlers = {
    'click' : function(e){ console.log('click event: ',e); },
    'mousemove' : function(e){ console.log('mousemove event: ',e); },
    'keyup' : function(e){ console.log('keyup event: ',e); }
};

var eObj = new Module(document.querySelector('#canvas'), 'mousemove', false);

Hope this helps you.

Blauharley
  • 4,186
  • 6
  • 28
  • 47