From 4e46675f948923d7698af0f9e488cc7caeeab4d2 Mon Sep 17 00:00:00 2001 From: Jiiks Date: Mon, 12 Feb 2018 01:04:07 +0200 Subject: [PATCH] add events for plugins --- client/src/modules/pluginapi.js | 28 +++++++++++++++++++++++++++- tests/plugins/Example/index.js | 12 ++++++------ 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/client/src/modules/pluginapi.js b/client/src/modules/pluginapi.js index f424b517..f7f0565d 100644 --- a/client/src/modules/pluginapi.js +++ b/client/src/modules/pluginapi.js @@ -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) } } diff --git a/tests/plugins/Example/index.js b/tests/plugins/Example/index.js index 53d5c868..49110781 100644 --- a/tests/plugins/Example/index.js +++ b/tests/plugins/Example/index.js @@ -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); + } } } \ No newline at end of file