var EventBus = { topices: {}, localTopies: {}, /** * 发布事件 * @param {string} topic 主题 * @param {object|string} value 数据 */ Publish: function (topic, value) { var uuid = window.uuid(8, 16) var format = typeof value === 'object' ? 'JSON' : 'STRING' var valstr = typeof value === 'object' ? JSON.stringify(value) : value localStorage.setItem('$$evt_' + topic, uuid + '_' + format + ':' + valstr) //发布本地事件 var tc = this.localTopies[topic] if (!!tc) { tc.forEach((item) => { try { item.func(item.uuid, value) } catch (error) { logerr(error) } }) } }, /** * 订阅事件 * @param {string} topic 主题 * @param {function} callback 回调 * @returns {string} 订阅ID */ Subscribe: function (topic, callback) { var tc = this.topices[topic] if (!tc) { tc = [] this.topices[topic] = tc } var uuid = window.uuid(8, 16) tc.push({ uuid, callback }) //订阅本地事件 tc = this.localTopies[topic] if (!tc) { tc = [] this.localTopies[topic] = tc } tc.push({ uuid: callback.name, callback }) return uuid }, /** * 取消订阅 * @param {string}} topic 主题 * @param {string} id 订阅ID */ UnSub: function (topic, id) { var tc = this.topices[topic] if (tc) { this.topices[topic] = tc.filter((x) => !x.uuid === id) } if (typeof id == 'function') { tc = this.localTopies[topic] if (tc) { this.localTopies[topic] = tc.filter((x) => !x.uuid === id.name) } } }, /** * 清理存储 */ ClearStore() { localStorage.clear() }, } window.addEventListener('storage', function (event) { if (event.key.indexOf('$$evt_') < 0) return var topic = event.key.split('_')[1] var tc = EventBus.topices[topic] if (tc && tc.length > 0) { var valstr = event.newValue.substr(event.newValue.indexOf(':') + 1) var flag = event.newValue.substr(0, event.newValue.indexOf(':')) var id = flag.substr(0, flag.indexOf('_')) var format = flag.substr(flag.indexOf('_') + 1) var valobj = format === 'JSON' ? JSON.parse(valstr) : valstr for (var j of tc) { try { j.callback(id, valobj) } catch {} } } })