eguneys
eguneys

Reputation: 6396

simplest way to use event emitter in ES6

This is my current implementation of an event emitter.

class Table {

  set onDiscard(cb) {
    this._onDiscard = cb;
  }

  notifyDiscard(s) {
    if (this._onDiscard) {
      this._onDiscard(s);
    }
  }
}

In the case of having multiple events this gets a burden.

What library/feature/implementation can I use so I can simplify this to a single line.

Upvotes: 2

Views: 4888

Answers (4)

hashwarp
hashwarp

Reputation: 3933

Here's a simple one that supports multiple handlers:

class Table {
    on(type, cb) {
        this['_on' + type] = this['_on' + type] || [];
        this['_on' + type].push(cb);
    }

    emit(type, args) {
        this['_on' + type] && this['_on' + type].forEach((cb) => { cb(args) });
    }
}

var table = new Table();

table.on('started', function() { alert('started'); });
table.emit('started');

Upvotes: 5

user663031
user663031

Reputation:

If you're using Ember, it has perfectly good mechanisms for emitters and notifiers. There's no reason not to use them. There's also no reason to use another, different class mechanism, just because it happens to exist in ES6, when Ember already provides one. Nor should you try to somehow awkwardly marry the Ember world with the ES6 class world.

Remember that ES6 classes (which some people say should not have been in the spec in the first place) are merely light syntactic sugar over JS prototype-based classes. So you should ask yourself the question: if I was already using Ember, would I implement my own emitter/notifier system using prototype-based classes? I doubt it. There's no reason to have two parallel class paradigms. Dance with the one you brought.

Upvotes: 0

Tesseract
Tesseract

Reputation: 8139

Why not make the event type a string?

class Table {
  on(eventType, cb) {
    this["_on" + eventType] = cb;
  }
  notify(eventType, s) {
    if(this["_on" + eventType]) {
      this["_on" + eventType](s);
    }
  }
}

Upvotes: 3

Gerard van Helden
Gerard van Helden

Reputation: 1602

Do you mean ES6 specifically or just ECMAScript? Since ES6 is backwards compatible you could use any event library in ES5 (javascript) out there.

I'd suggest Backbone, as what you're doing seems to be model/view logic, which Backbone is actually very good at. It is very minimalistic, has it's own event emitter / listener (see Events section) implementation which is very similar to the one used by the DOM internally, and it helps separating your view and model logic very well.

I have implemented a simple app recently as a proof of concept using Backbone with ES6 and it's compatible just the way you'd expect. Extending the base classes using ES6's extend does just what underscore's extend does when calling extend as suggested in Backbone's docs.

I used babeljs for transpilation in that case.

Upvotes: 1

Related Questions