mframejs
Version:
simple framework
64 lines (50 loc) • 1.58 kB
text/typescript
/**
* simple event aggregator for sending messages between components/attributes etc
*
*/
export class EventAggregator {
private channels: any;
constructor() {
this.channels = {};
}
// todo, do we want a async option ?
// todo, do we want to upper/lower case all channels? less chance for typos..
/**
* publish to channel
*
*/
public publish(channel: string, ...args: any[]): void {
if (Array.isArray(this.channels[channel])) {
for (let i = 0, len = this.channels[channel].length; i < len; i++) {
this.channels[channel][i].apply(this, args);
}
} else {
// if no one is listening then do we really need to do anything ?
}
}
/**
* unsubscribes to channel
*
*/
public unsubscribe(channel: string, func: Function): void {
if (Array.isArray(this.channels[channel])) {
for (let i = 0, len = this.channels[channel].length; i < len; i++) {
if (this.channels[channel][i] === func) {
this.channels[channel].splice(i, 1);
}
}
} else {
// channel does not exist, great!
}
}
/**
* subscribes to channel
*
*/
public subscribe(channel: string, func: Function): void {
if (!Array.isArray(this.channels[channel])) {
this.channels[channel] = [];
}
this.channels[channel].push(func);
}
}