EventBus.js
//创建EventBus对象
let EventBus = function () {
console.log("eventbus init...");
};
//准备数组容器
var arrbus = [];
//添加方法
EventBus.prototype = {
emit: function (key, data) {
let list = arrbus[key];
if (list == null) return;
let len = list.length - 1;
//反向遍历,防止在订阅者在回调中移除自身带来的下标错位
for (var i = len; i > -1; --i) {
list[i](data);
}
},
off: function (key, action) {
let list = arrbus[key];
if (key == null || list == null) return;
if (action == null) {
arrbus[key] = null;
} else {
let actionIndex = arrbus[key].indexOf(action)
arrbus[key].splice(actionIndex,1)
}
},
on: function (key, action) {
if (key == null || action == null) return;
if (!arrbus[key]) {
arrbus[key] = []
}
arrbus[key].push(action);
},
}
var eventBus = new EventBus()
module.exports = {
eventBus: eventBus
}
引入并使用
const EventBus = require('../utils/eventBus.js');
监听
EventBus.eventBus.on('childIndex', this.childIndexWatchBack)
发送
EventBus.eventBus.emit('childIndex', e.target.dataset.index)
取消某个监听
EventBus.eventBus.off('childIndex', this.childIndexWatchBack)
取消全部监听
EventBus.eventBus.off('childIndex')
网友评论