12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- /* eslint-disable */
- /**
- * 突然想到,无论是web端、小程序还是node中,似乎都不需要这货,或者其他第三方库……因为node中有类似的API,而web端和小程序中可以通过在document上手动触发CustomEvent、注册监听器来实现,不过确实麻烦一些。Vue中还可以直接通过一个通信总线组件来实现。
- */
- /**
- * 如果想让注册的回调只调用一次就自动注销,在注册的回调中执行注销即可。
- */
- export class MessageCenter {
- constructor() {
- this._recorder = {};
- }
- logInvalidParam() {
- console.error("MessageCenter: invalid parameter.");
- }
- subscribe(message, callback) {
- if (typeof message !== "string" || typeof callback !== "function") {
- this.logInvalidParam();
- return;
- }
- if (!Object.prototype.hasOwnProperty.call(this._recorder, message)) {
- this._recorder[message] = [];
- }
- this._recorder[message].push(callback);
- }
- unsubscribe(message, callback) {
- if (typeof message !== "string" || typeof callback !== "function") {
- this.logInvalidParam();
- return;
- }
- if (Object.prototype.hasOwnProperty.call(this._recorder, message)) {
- const idx = this._recorder[message].indexOf(callback);
- if (idx !== -1) {
- this._recorder[message].splice(idx, 1);
- }
- }
- }
- publish(message, param) {
- if (Object.prototype.hasOwnProperty.call(this._recorder, message)) {
- this._recorder[message].forEach((callback) => {
- callback(param);
- });
- }
- }
- }
|