我有这个酒吧子代码
export const subscribe = (eventName, callback) => {
pubsub.addEventListener(eventName, (e, data) => {
callback(e.detail);
});
};
export const unsubscribe = (eventName, callback) => {
pubsub.removeEventListener(eventName, callback);
};
export const publish = (eventName, data) => {
pubsub.dispatchEvent(new CustomEvent(eventName, { detail: data }));
};
但是取消订阅似乎不起作用,我不知道为什么。
const setTargetFn = () => {
unsubscribe("setTargetUnitId", setTargetFn);
createMessage("Great job! Now attack it by pressing 1 and going near it", 0);
};
subscribe("setTargetUnitId", setTargetFn);
即使在我取消订阅后,订阅的事件仍然被调用...请帮忙
这是你的问题:
unsubscribe("setTargetUnitId", setTargetFn);
不是
setTargetFn
必须注销。实际要取消注册的功能是...
(e, data) => { callback(e.detail); }
...因为那是你传递给
pubsub.addEventListener
.
如果您直接注册
callback
,您的代码将正常工作:
var subscribe = (eventName, callback) => {
pubsub.addEventListener(eventName, callback);
};