JSFiddle - React, Tailwind, and code Playground

by paradite

JavaScript

// Write your code here.
class Notifier {
  constructor() {

  }

  on(eventName, callback) {

  }

  trigger(eventName, ...parameters) {

  }
}

var notifier = new Notifier();

var listenerJohn = notifier.on('MY_EVENT', function (action, item) {
  console.log(`John is ${action} ${item}`);
});
var listenerJane = notifier.on('MY_EVENT', function (action, item) {
  console.log(`Jane is ${action} ${item}`);
});

notifier.trigger('MY_EVENT', 'eating', 'a burger');
// Should see the following in the console:
// John is eating a burger
// Jane is eating a burger

/*
Write a Notifier class that supports the following operations:

1. Constructor.

var notifier = new Notifier();

2. Listening to events.

var listenerJohn = notifier.on('MY_EVENT', function (action, item) {
  console.log(`John is ${action} ${item}`);
});
var listenerJane = notifier.on('MY_EVENT', function (action, item) {
  console.log(`Jane is ${action} ${item}`);
});

3. Triggering of events.

This particular example should lead to both callbacks
above being invoked with 'eating' and 'a burger' as parameters:

notifier.trigger('MY_EVENT', 'eating', 'a burger');
// Should see the following in the console:
// John is eating a burger
// Jane is eating a burger

4. Unsubscribing a listener from existing events.
Note that `off` is not a method no `Notifier`.

`listenerJohn` is the reference returned by `on` above.

listenerJohn.off();
notifier.trigger('MY_EVENT', 'eating', 'a burger');
// Only Jane's callback is invoked.
// Jane is eating a burger

*/