封装事件订阅来进行非父子组件的传值(React)

const list={}

// 将事件名和事件函数装进事件池里
function  $on(name,func) {
    if(!name || !func) return;
    if(!Object.keys(list).includes(name)){
        list[name]=func;
    }
}
// 根据事件名称搜索事件池 找到执行
function $emit(name,...arg) {
    if(!name) return;
    if(Object.keys(list).includes(name)){
        list[name](...arg)
    }
}

// 执行完并且不在需要后 清除事件
function $off(name) {
    if(!name) return;
    if(Object.keys(list).includes(name)){
        list[name]=null;
        delete list[name]
    }
}
export {
    $on,
    $emit,
    $off,
}
posted @ 2019-12-21 21:37  温润如玉Ayu  阅读(266)  评论(0编辑  收藏  举报