From d4e8e940251e29b66336a0f5c9b9da82f5939713 Mon Sep 17 00:00:00 2001 From: Ryan Wyllie Date: Tue, 17 Jul 2018 14:50:00 +0800 Subject: [PATCH] MDL-63044 javascript: add simple pubsub implementation --- lib/amd/build/pubsub.min.js | Bin 0 -> 270 bytes lib/amd/src/pubsub.js | 74 ++++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 lib/amd/build/pubsub.min.js create mode 100644 lib/amd/src/pubsub.js diff --git a/lib/amd/build/pubsub.min.js b/lib/amd/build/pubsub.min.js new file mode 100644 index 0000000000000000000000000000000000000000..871bb59c16d976a5aa11f7fdbea7fc93be2501bf GIT binary patch literal 270 zcmZ9G!488U5JZ2aCj*g~_A2GruP`297YnID1JVof?-gTg;$^eDnRzp)2kSKHdNxD{ zi=7;y=_~zBij. + +/** + * A simple Javascript PubSub implementation. + * + * @module core/pubsub + * @copyright 2018 Ryan Wyllie + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +define([], function() { + + var events = {}; + + /** + * Subscribe to an event. + * + * @param {string} eventName The name of the event to subscribe to. + * @param {function} callback The callback function to run when eventName occurs. + */ + var subscribe = function(eventName, callback) { + events[eventName] = events[eventName] || []; + events[eventName].push(callback); + }; + + /** + * Unsubscribe from an event. + * + * @param {string} eventName The name of the event to unsubscribe from. + * @param {function} callback The callback to unsubscribe. + */ + var unsubscribe = function(eventName, callback) { + if (events[eventName]) { + for (var i = 0; i < events[eventName].length; i++) { + if (events[eventName][i] === callback) { + events[eventName].splice(i, 1); + break; + } + } + } + }; + + /** + * Publish an event to all subscribers. + * + * @param {string} eventName The name of the event to publish. + * @param {any} data The data to provide to the subscribed callbacks. + */ + var publish = function(eventName, data) { + if (events[eventName]) { + events[eventName].forEach(function(callback) { + callback(data); + }); + } + }; + + return { + subscribe: subscribe, + unsubscribe: unsubscribe, + publish: publish + }; +}); -- 2.36.1