// 基于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 自定义事件通信
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 一、组件的定义与使用 1、vue文件的组成 (1)模板页面 (2)js模块对象 (3)样式 2、基本使用 (1)引...
- ***组件自己的数据:this.state={a:'test'} 设置this.setState({a:'b'})...
- 观察者模式 观察者模式是一种创建松散耦合代码的技术,它定义对象间一种一对多的依赖关系,当一个对象的状态发生改变时,...
- https://www.bilibili.com/video/BV15741177Eh?p=60&spm_id_f...