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

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

不言
不言forward
2018-10-27 16:43:062091browse

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');

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;
}

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'

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!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete