Home > Web Front-end > JS Tutorial > Understanding the javascript event receiving and sending mechanism (code example)

Understanding the javascript event receiving and sending mechanism (code example)

不言
Release: 2018-10-27 16:43:24
forward
2139 people have browsed it

The content this article brings to you is about the understanding of the JavaScript event receiving and sending mechanism (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

In fact, the event sending and receiving mechanism is very simple, I just didn’t think about it

It will be used more in the node module
such as

var events=require('events');
var eventEmitter=new events.EventEmitter();
eventEmitter.on('say',function(name){
    console.log('Hello',name);
})
eventEmitter.emit('say','Jony yu');
Copy after login

In vue, the transmission of parent-child components also uses the sending and receiving of events, emit and on to make

Then let’s take a look

function myEvent() {

    this.on = function() {
        if (!this.handles) {
            this.handles = {};
        }
        if (!this.handles[eventName]) {
            this.handles[eventName] = [];
        }
        this.handles[eventName].push(callBack);
    }

    this.emit = function() {
        if (this.handles[eventName]) {
            for (var i = 0; o < this.handles[eventName].length; i++) {
                this.handles[eventName][i](obj);
            }
        }
    }
    return this;
}
Copy after login

Test it

var event1=new Events();
var event2=new Events();
event1.on('say',function(){
    console.log('Jony event1');
});
event2.on('say',function(){
    console.log('Jony event2');
})
event1.emit('say');
event2.emit('say');
//event1、event2之间的事件监听互相不影响
//输出结果为'Jony event1' 'Jony event2'
Copy after login

This is the mechanism for sending and receiving events.

The above is the detailed content of Understanding the javascript event receiving and sending mechanism (code example). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template