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

// 基于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 自定义事件通信)