CustomEvent
您可以轻松地在此处构建抽象:
const handlers = {};
window.publish = (topic, message) => {
var ev = new CustomEvent('pubsub', {
detail: { topic, message },
});
document.body.dispatchEvent(ev);
};
window.subscribe = (topic, handler) => {
const topicHandlers = handlers[topic] || [];
topicHandlers.push(handler);
handlers[topic] = topicHandlers;
};
window.unsubscribe = (topic, handler) => {
const topicHandlers = handlers[topic] || [];
const index = topicHandlers.indexOf(handler);
index >= 0 && topicHandlers.splice(index, 1);
};
document.body.addEventListener('pubsub', ev => {
const { topic, message } = ev.detail;
const topicHandlers = handlers[topic] || [];
topicHandlers.forEach(handler => handler(message));
});
(有关演示,请参阅:https ://jsfiddle.net/qo5nca71/ )
在大多数情况下,这应该足够了。如果你想获得更多的“安全性”(例如,微前端不能改变抽象,这些抽象在上面的 impl. 中只是全局可用的)我建议使用更复杂的方法,比如 Piral 中的事件机制(参见https:// github.com/smapiot/piral)。