lib/amd/src/pubsub.js

  1. // This file is part of Moodle - http://moodle.org/
  2. //
  3. // Moodle is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU General Public License as published by
  5. // the Free Software Foundation, either version 3 of the License, or
  6. // (at your option) any later version.
  7. //
  8. // Moodle is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  15. /**
  16. * A simple Javascript PubSub implementation.
  17. *
  18. * @module core/pubsub
  19. * @copyright 2018 Ryan Wyllie <ryan@moodle.com>
  20. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  21. */
  22. import Pending from 'core/pending';
  23. const events = {};
  24. /**
  25. * Subscribe to an event.
  26. *
  27. * @param {string} eventName The name of the event to subscribe to.
  28. * @param {function} callback The callback function to run when eventName occurs.
  29. */
  30. export const subscribe = function(eventName, callback) {
  31. events[eventName] = events[eventName] || [];
  32. events[eventName].push(callback);
  33. };
  34. /**
  35. * Unsubscribe from an event.
  36. *
  37. * @param {string} eventName The name of the event to unsubscribe from.
  38. * @param {function} callback The callback to unsubscribe.
  39. */
  40. export const unsubscribe = function(eventName, callback) {
  41. if (events[eventName]) {
  42. for (var i = 0; i < events[eventName].length; i++) {
  43. if (events[eventName][i] === callback) {
  44. events[eventName].splice(i, 1);
  45. break;
  46. }
  47. }
  48. }
  49. };
  50. /**
  51. * Publish an event to all subscribers.
  52. *
  53. * @param {string} eventName The name of the event to publish.
  54. * @param {any} data The data to provide to the subscribed callbacks.
  55. */
  56. export const publish = function(eventName, data) {
  57. const pendingPromise = new Pending("Publishing " + eventName);
  58. if (events[eventName]) {
  59. events[eventName].forEach(function(callback) {
  60. callback(data);
  61. });
  62. }
  63. pendingPromise.resolve();
  64. };