message-center.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /* eslint-disable */
  2. /**
  3. * 突然想到,无论是web端、小程序还是node中,似乎都不需要这货,或者其他第三方库……因为node中有类似的API,而web端和小程序中可以通过在document上手动触发CustomEvent、注册监听器来实现,不过确实麻烦一些。Vue中还可以直接通过一个通信总线组件来实现。
  4. */
  5. /**
  6. * 如果想让注册的回调只调用一次就自动注销,在注册的回调中执行注销即可。
  7. */
  8. export class MessageCenter {
  9. constructor() {
  10. this._recorder = {};
  11. }
  12. logInvalidParam() {
  13. console.error("MessageCenter: invalid parameter.");
  14. }
  15. subscribe(message, callback) {
  16. if (typeof message !== "string" || typeof callback !== "function") {
  17. this.logInvalidParam();
  18. return;
  19. }
  20. if (!Object.prototype.hasOwnProperty.call(this._recorder, message)) {
  21. this._recorder[message] = [];
  22. }
  23. this._recorder[message].push(callback);
  24. }
  25. unsubscribe(message, callback) {
  26. if (typeof message !== "string" || typeof callback !== "function") {
  27. this.logInvalidParam();
  28. return;
  29. }
  30. if (Object.prototype.hasOwnProperty.call(this._recorder, message)) {
  31. const idx = this._recorder[message].indexOf(callback);
  32. if (idx !== -1) {
  33. this._recorder[message].splice(idx, 1);
  34. }
  35. }
  36. }
  37. publish(message, param) {
  38. if (Object.prototype.hasOwnProperty.call(this._recorder, message)) {
  39. this._recorder[message].forEach((callback) => {
  40. callback(param);
  41. });
  42. }
  43. }
  44. }