Vue package event function

/*
事件池
eventList = {
handle:[fn1,fn2,fn3]
abc:[fn1,fn2,fn3]
}
||
eventList = {

}

$ on (eventName, callback)
to determine the current name of the event exists, if it does not exist to create value is a key event name value as an array
to callback push into an array

If the event name exists directly added to the array to


$emit(eventName,[params])

The current name of the event to determine whether there is, if it exists through the array, get all the functions and perform. Then params as arguments passed to a function to


$off(eventName,[callback])


The current name of the event to determine whether there is, if there continues to determine whether there is a second argument, if there is to find the index with respect to the function and then removed in an array
if it will clear the entire array does not exist
* /

const eventList = {}


const $on = (eventName,callback)=>{
if(!eventList[eventName]){
eventList[eventName] = [];
}
eventList[eventName].push(callback)
}

 

$ EMIT = const (eventName, the params) => {
IF (EventList [eventName]) {
the let ARR = EventList [eventName];
arr.map ((CB) => {// CB is traversed in each of the array function will return a map Item
CB (the params);
})
}

}

const $off = (eventName,callback)=>{
if(eventList[eventName]){
if(callback){
let index = eventList[eventName].indexOf(callback);
eventList[eventName].splice(index,1);
}else{
eventList[eventName].length = 0;
}
}
}


function fn1(val){
console.log(111,val)
}

function fn2(val){
console.log(222,val)
}

function fn3(val) {
console.log(333,val)
}

 

$on("handle",fn1)
$on("handle",fn2)
$on("handle",fn3)
$off("handle",fn1)
$emit("handle","abc")

Guess you like

Origin www.cnblogs.com/superclound/p/11247680.html