EventEmitter 不同框架/不同react应用 之间交互桥梁

import EventEmitter from 'eventemitter3';

 

EventEmitter.on('eventName', handleFunction); 可以监听多个相同的eventName事件, 这是因为它是把监听的每一个事件都放入了同一个event list中, 这样每次接收到信息时会把event list 里面所有的事件都调用一次

而测试时用的window它只是一个对象, 如果多个相同的组件都 挂在方法在window上, 只会在最后一个组件中调用此方法.例如widget pages

 

利用EventEmitter更新数据方案:

  1. 如果A项目和B项目接口返回的数据格式相同, 那么可以直接拿A项目的数据来更新B项目, 就不需要请求API了
  2. 如果A项目和B项目接口返回的数据格式不同, 那么就需要对字段进行处理, 以此来保持一致, 这样做有两个问题:
    1. 需要处理字段, 很麻烦
    2. 不方便后期维护, 每当API新增一个字段, 可能就需要对新字段进行处理

所以, 对于这种情况, 我觉得最好的做法就是通过请求API来reload数据

 

拓展

1.只触发一次

EventEmitter.prototype.once = function(events,handler){
    // no events,get out!
    if(! events)
        return; 
 
    // Ugly,but helps getting the rest of the function 
    // short and simple to the eye ... I guess...
    if(!(events instanceof Array))
        events = [events];
 
    var _this = this;
 
    var cb = function(){
        events.forEach(function(e){     
            // This only removes the listener itself 
            // from all the events that are listening to it
            // i.e.,does not remove other listeners to the same event!
            _this.removeListener(e,cb); 
        });
 
        // This will allow any args you put in xxx.emit('event',...) to be sent 
        // to your handler
        handler.apply(_this,Array.prototype.slice.call(arguments,0));
    };
 
    events.forEach(function(e){ 
        _this.addListener(e,cb);
    }); 
};

  

posted @ 2020-10-13 17:47  一路向北√  阅读(174)  评论(0编辑  收藏  举报

web应用开发&研究 -

业精于勤而荒于嬉。

工作,使我快乐。


Font Awesome | Respond.js | Bootstrap中文网