You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
39 lines
1.4 KiB
JavaScript
39 lines
1.4 KiB
JavaScript
let PubSub = ()=>{
|
|
// state:
|
|
let subscriptions_by_event = {}; // by event name, that is
|
|
let subscriptions_by_name = {}; // subscriptions can be named, for easy unsubscribing
|
|
|
|
// methods:
|
|
let pub = (e, ...params)=>{
|
|
if(subscriptions_by_event[e]){
|
|
subscriptions_by_event[e].forEach(subscription=>subscription.cb(...params))
|
|
}
|
|
};
|
|
let sub = (e, cb, name)=>{ // 'name' is for unsubbing
|
|
if(typeof subscriptions_by_event[e] === 'undefined'){
|
|
subscriptions_by_event[e] = [];
|
|
}
|
|
|
|
let subscription = { e, cb, name: name || '' };
|
|
|
|
subscriptions_by_event[e].push(subscription);
|
|
if(subscription.name !== ''){
|
|
if(typeof subscriptions_by_name[name] !== 'undefined'){ console.warn('Already subscription with name "'+name+'". Overwriting nonetheless.'); }
|
|
subscriptions_by_name[name] = subscription;
|
|
}
|
|
};
|
|
let unsub = (name)=>{
|
|
// check if such a named subscription exists:
|
|
if(typeof subscriptions_by_name[name] !== 'undefined'){
|
|
// get ref to subscription object for later:
|
|
let subscription = subscriptions_by_name[name];
|
|
// delete subscription from both lists:
|
|
subscriptions_by_event[subscription.e].splice(subscriptions_by_event[subscription.e].indexOf(subscription), 1);
|
|
delete subscriptions_by_name[name];
|
|
}
|
|
};
|
|
|
|
return {pub, sub, unsub};
|
|
}
|
|
|
|
export default PubSub; |