美文网首页
2022-04-23 CustomEvent 自定义事件通信

2022-04-23 CustomEvent 自定义事件通信

作者: FConfidence | 来源:发表于2022-04-23 00:35 被阅读0次
    // 基于CustomEvent的通信机制
    let eventGlobalState = {
      a: 1,
      b: '2',
      c: true,
    };
    
    const MY_CUSTOM_EVENT_NAME = 'MY_CUSTOM_EVENT_NAME';
    
    function noop() {}
    
    // 事件监听
    document.addEventListener(MY_CUSTOM_EVENT_NAME, (event) => {
      console.log(event);
      const {
        detail: { type, params, callback = noop },
      } = event;
      let newEventGlobalState = JSON.parse(JSON.stringify(eventGlobalState));
      if (type === 'get') {
        if (Array.isArray(params) && params.length) {
          const newTempEventGlobalState = {};
          params.forEach((keyItem) => {
            newTempEventGlobalState[keyItem] = newEventGlobalState[keyItem];
          });
          newEventGlobalState = newTempEventGlobalState;
        }
      }
      else if (type === 'set') {
        eventGlobalState = {
          ...eventGlobalState,
          ...params,
        };
        newEventGlobalState = {
          ...newEventGlobalState,
          ...params,
        };
      }
    
      callback(newEventGlobalState);
    });
    
    // 事件派发
    function dispatch({ type, params, callback = noop }) {
      const detailParams = {
        type,
        params,
        callback: noop,
      };
      const cv = new CustomEvent(MY_CUSTOM_EVENT_NAME, {
        detail: detailParams,
      });
      return new Promise((resolve, reject) => {
        if (type === 'get') {
        } else if (type === 'set') {
        }
        cv.detail.callback = function (response) {
          callback(response);
          resolve(response);
        };
        document.dispatchEvent(cv);
      });
    }
    
    window.dispatch = dispatch;
    
    // await dispatch({ type: 'set', params: { a: 3, d: 'ddd' } } )
    // await dispatch({ type: 'get', params: ['c'] })
    

    相关文章

      网友评论

          本文标题:2022-04-23 CustomEvent 自定义事件通信

          本文链接:https://www.haomeiwen.com/subject/msboertx.html