Search code examples
javascriptjqueryclasscustom-event

Custom event acomplished in Class


The following two code samples were given to me at a job interview and I couldn't manage to make it work:

//CODE1:
var e = new Event();

e.on('myevent', function (a, b) {
    console.log(a + ' ' + b);
});

e.trigger('myevent', ['Hello', 'world']);


//CODE2:  
e.on('hello', function() {
    console.log('Hello');
    this.trigger('world');
}).on('world', function() {
    console.log('World');
}).trigger('hello');

So the given two codes can't be modified, the Class called Event() should work so both the two code samples would output "Hello world". Now, I'm not asking for a complete answer. I'm not that good at Classes and Custom events in Javascript. I know the basics, but it's not really in my hands yet, if You know what I mean. I've been searching for tutorials, but I need someone "smarter" to tell me where should I start, providing maybe some links for good tutorials for my problem.

Thanks!


Solution

  • Demo http://jsfiddle.net/uAQn9/

    Code:

    function Event() {
    
    }
    
    Event.prototype = {
    
      trigger:function(eventName, arParam) {
        $(window).trigger(eventName, arParam);
      },
    
      on: function(eventName, cb) {
        var event = this;
        $(window).on(eventName, function(e) {
          var args = Array.prototype.slice.call(arguments);
          cb.apply(event, args.slice(1));
        });
        return this;
      }
    }
    
    //CODE1:
    var e = new Event();
    
    e.on('myevent', function (a, b) {
        console.log(a + ' ' + b);
    });
    
    e.trigger('myevent', ['Hello', 'world']);
    
    
    //CODE2:  
    e.on('hello', function() {
        console.log('Hello');
        this.trigger('world');
    }).on('world', function() {
        console.log('World');
    }).trigger('hello');