Command Palette

Search for a command to run...

Hectal
Phase 15: Patterns, Security and Interviews
JavaScript · Exercise 3 of 6 PreviousNext
Intermediate

Build an event emitter

Write a class Emitter (the observer pattern from Topic 15.2) with these methods:

on(event, fn) adds a listener and returns a function that removes it. off(event, fn) removes a listener. emit(event, ...args) calls every listener of that event with all the arguments, in the order they were added; emitting an event with no listeners does nothing. once(event, fn) adds a listener that runs only the first time.

Then use it: make the button emit "like" with the number 1, and have a listener add that number to the counter in #likes.

What Check tests

  1. on and emit call listeners in order with all arguments
  2. Emitting an event nobody listens to does nothing
  3. off removes a listener
  4. on returns a function that unsubscribes
  5. once runs a listener only the first time
  6. Clicking Like twice shows 2

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

Runs in your browser. Your code is saved here.

Your page

Press Run to see the page.

Console

Nothing logged yet.