Event emitter's listening events

php中世界最好的语言
Release: 2018-04-08 17:50:03
Original
4761 people have browsed it

This time I will bring you the monitoring events of Event emitter. What are the precautions when using Event emitter to monitor events. The following is a practical case, let’s take a look.

What is an Event Emitter?

Event emitter sounds like it just triggers an event, and anything can listen to this event.

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}`;
});
Copy after login

Let’s get started.

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

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);
}
Copy after login

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

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

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);
    });
  }
}
Copy after login

This call function accepts the event name, which is the name we want to "call", and the data we want to pass 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);
  }
}
Copy after login

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

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

When we call the unregistration function, the function we delete depends on the filtering method (Array filter) of the subscription function collection.

Say goodbye to memory leaks!

The above is the detailed content of Event emitter's listening events. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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 [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!