Home  >  Article  >  Web Front-end  >  The secret behind JavaScript EventEmitter

The secret behind JavaScript EventEmitter

亚连
亚连Original
2018-05-28 11:21:231148browse

Here, our goal is to create our own Event Emitter to understand the secret behind it. So, let's take a look at how the following code works. Friends who need it can refer to it

What is Event Emitter?

Event emitter sounds like it just triggers an event. This event can be anything. All can be monitored.

Imagine a scenario where in your asynchronous code, you "call" some events to occur, and let other parts of you hear your "call" and register their thoughts.

There are a number of different implementations of the Event Emitter pattern for different purposes, but the basic idea is to provide a framework with event management and the ability to subscribe to them.

Here, our goal is to create our own Event Emitter to understand the secret behind it. So, let's see how the code below works.

let input = document.querySelector("input[type="text"]");
let button = document.querySelector("button");
let h1 = document.querySelector("h1");

button.addEventListener("click", () => {
  emitter.emit("event:name-changed", { name: input.value });
});

let emitter = new EventEmitter();
emitter.subscribe("event:name-changed", data => {
  h1.innerHTML = `Your name is: ${data.name}`;
});

Let's get started.

class EventEmitter {
  constructor() {
    this.events = {};
  }
}

We first create an EventEmiiter class and initialize the events empty object property. The purpose of this events attribute is to store our event collection. This events object uses the event name as the key and the subscriber collection as the value. (You can think of each subscriber as a function).

Subscription function

subscribe(eventName, fn) {
  if (!this.events[eventName]) {
    this.events[eventName] = [];
  }

  this.events[eventName].push(fn);
}

This subscription function gets the event name, in our previous example, it was "event:name -changed" and pass in a callback that is called when someone calls the emit (or screams) event.

One of the advantages of functions in JavaScript is that the function is the first object, so we can pass the function as a parameter of another function just like we did with our subscription method before.

If this event is not registered, we need to set an initial value for it for the first time, the event name as the key and initialize an empty array assigned to it, and then we put the function into this array so that we want Call this event through emit.

Call function

emit(eventName, data) {
  const event = this.events[eventName];
  if (event) {
    event.forEach(fn => {
      fn.call(null, data);
    });
  }
}

This call function accepts the event name, which is the name we want to "call", and the name we want to pass The data given to this event. If this event exists in our events, we will loop through all subscribed methods with the data.

Using the above code can do all the things we said. But we still have a problem. We need a way to unregister these subscriptions when we no longer need them, because if you don't do this you will create a memory leak.

Let's solve this problem by returning an unregistration method in the subscription function.

subscribe(eventName, fn) {
  if (!this.events[eventName]) {
    this.events[eventName] = [];
  }

  this.events[eventName].push(fn);

  return () => {
    this.events[eventName] = this.events[eventName].filter(eventFn => fn !== eventFn);
  }
}

Because JavaScript functions are first objects, you can return a function within a function. So now we can call the unregister function as follows:

let unsubscribe = emitter.subscribe("event:name-changed", data => console.log(data));

unsubscribe();

When we call the unregister function, the function we delete depends on the collection of subscribed functions Filtering method (Array filter).

Say goodbye to memory leaks!

The above is the detailed content of The secret behind JavaScript EventEmitter. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn