Explanation of node event mechanism

小云云
Release: 2018-01-26 13:31:34
Original
1428 people have browsed it

This article mainly introduces the event mechanism of node. This article implements a simple event mechanism with publish/subscribe mode to clarify the implementation ideas of the EventEmitter class. If you are interested, you can learn more. I hope it can help. Everyone.

Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient.

In the official documentation of nodejs, it is clearly written One of the features of node is event-driven, which shows that it is very important. Looking at the source code, we can see that its event mechanism is the EventEmitter class written in js, which is very elegantly written and applies the publish/subscribe model.

By implementing a simple event mechanism with publish/subscribe mode, we can clarify the implementation ideas of the EventEmitter class

Publish/Subscribe (publish/subscribe mode)

ANAlogy

What we are talking about is a pattern. The word pattern sounds very abstract. Let’s give a chestnut first. Suppose there is a newspaper organization that provides morning, afternoon, and evening newspapers. If you want to read a certain newspaper, you need to subscribe to the newspaper organization. When the corresponding newspaper is released, the newspaper organization will notify you to pick up the newspaper.

In this process, the newspaper organization has implemented two functions. One is to accept customer subscriptions; the other is to publish different types of newspapers. When a newspaper is published, customers who subscribe to that type of newspaper will receive notifications.

This newspaper organization is the event mechanism we want to implement.

Purpose

It can be seen from the above example: 1. Publish the newspaper; 2. Give the newspaper to the customer; this Due to the existence of the newspaper organization, the continuous process can be subscribed first and then published. When it is published, it will be automatically sent to the customer, realizing the separation of action time. This is also the advantage of the publish/subscribe system.

Implementation ideas

We have 3 types of newspapers, corresponding to 3 events, and customers must be notified when each event occurs. The corresponding data format can be as follows:


var Event = { morning: event1, noon: event2, night: event3 }
Copy after login

Since each newspaper may be subscribed by more than one person, the format can be optimized like this:


var Event = { morning: [e11, e12,...], noon: [e21, e22], night: event3 }
Copy after login

When a user subscribes, we add its event to the corresponding array; when the event is published, the corresponding event is executed. To put it bluntly, store it first and then use it.

The specific code is as follows:

1.on means subscribing, adding the event to the corresponding array
2.emit means publishing, adding the data in the corresponding array Take it out and execute
3.off means deleting useless events


var Event = { on: function(key, listener) { if (!this.__events) { this.__events = {} } if (!this.__events[key]) { this.__events[key] = []; } if (_indexOf(this.__events[key], listener) == -1 && typeof listener === 'function') { this.__events[key].push(listener) } }, emit: function(key) { if (!this.__events || !this.__events[key]) return //取得每次订阅不同的参数 var arg = Array.prototype.slice.call(arguments, 1) || []; var listeners = this.__events[key]; var len = listeners.length; for (var i=0; i -1) && listeners.splice(index, 1); } return this } } var _indexOf = function(array,key){ if (array === null) return -1 var i = 0, length = array.length for (; i < length; i++) if (array[i] === key) return i return -1 } //调用 Event.on('console1', function(num) { console.log(num); // 1 }); Event.emit('console1', 1)
Copy after login

node’s EventEmitter

node’s EventEmitter basic logic Basically the same as the example provided above, just more complicated.

1. Subscribe to events on


function _addListener(target, type, listener, prepend) { var m; var events; var existing; if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); events = target._events; ... if (typeof existing === 'function') { // Adding the second element, need to change to array. existing = events[type] = prepend ? [listener, existing] : [existing, listener]; } else { // If we've already got an array, just append. if (prepend) { existing.unshift(listener); } else { existing.push(listener); } } return target; } EventEmitter.prototype.addListener = function addListener(type, listener) { return _addListener(this, type, listener, false); }; EventEmitter.prototype.on = EventEmitter.prototype.addListener;
Copy after login

2. Publish events


EventEmitter.prototype.emit = function emit(type) { ... handler = events[type]; switch (len) { // fast cases case 1: emitNone(handler, isFn, this); break; case 2: emitOne(handler, isFn, this, arguments[1]); break; case 3: emitTwo(handler, isFn, this, arguments[1], arguments[2]); break; case 4: emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); break; // slower default: args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; emitMany(handler, isFn, this, args); } }
Copy after login

At this point, I believe everyone already understands the implementation idea of EventEmitter.

Related recommendations:

Implementation of PHP event mechanism

Event mechanism and blocking in jq and js

JavaScript event mechanism

The above is the detailed content of Explanation of node event mechanism. 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 admin@php.cn
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!