add events for plugins

This commit is contained in:
Jiiks 2018-02-12 01:04:07 +02:00
parent 4a7a9ae1db
commit 4e46675f94
2 changed files with 33 additions and 7 deletions

View File

@ -9,6 +9,7 @@
*/
import { ClientLogger as Logger } from 'common';
import Events from './events';
export default class PluginApi {
@ -31,10 +32,35 @@ export default class PluginApi {
};
}
get eventSubs() {
return this._eventSubs || (this._eventSubs = []);
}
eventSubscribe(event, callback) {
if (this.eventSubs.find(e => e.event === event)) return;
this.eventSubs.push({
event,
callback
});
Events.on(event, callback);
}
eventUnsubscribe(event) {
const index = this.eventSubs.findIndex(e => e.event === event);
if (index < 0) return;
Events.off(event, this.eventSubs[0].callback);
this.eventSubs.splice(index, 1);
}
eventUnsubscribeAll() {
this.eventSubs.forEach(event => {
Events.off(event.event, event.callback);
});
this._eventSubs = [];
}
get Events() {
return {
subscribe: this.eventSubscribe.bind(this),
unsubscribe: this.eventUnsubscribe.bind(this),
unsubscribeAll: this.eventUnsubscribeAll.bind(this)
}
}

View File

@ -2,23 +2,23 @@ module.exports = (Plugin, Api, Vendor) => {
const { $, moment, _ } = Vendor;
const { Events, Logger } = Api;
const test = 'Testing';
return class extends Plugin {
test() {
return test;
}
onStart() {
Events.subscribe('TEST_EVENT', this.eventTest);
Logger.log('onStart');
return true;
}
onStop() {
Events.unsubscribeAll();
Logger.log('onStop');
return true;
}
eventTest(e) {
Logger.log(e);
}
}
}