工具類 event.js
var events = {}
function on(name, self, callback) {
var tuple = [self, callback]
var callbacks = events[name]
if (Array.isArray(callbacks)) {
callbacks.push(tuple)
} else {
events[name] = [tuple]
}
}
function remove(name, self) {
var callbacks = events[name]
if (Array.isArray(callbacks)) {
events[name] = callbacks.filter((tuple) => {
return tuple[0] !== self
})
}
}
function emit(name, data) {
var callbacks = events[name]
if (Array.isArray(callbacks)) {
callbacks.map((tuple) => {
var self = tuple[0]
var callback = tuple[1]
callback.call(self, data)
})
}
}
exports.on = on
exports.remove = remove
exports.emit = emit
使用方法
例如:
組件A注冊 changeTab 事件, 組件B中, 選擇了tab,并主動告知組件A
組件A注冊事件
mounted () {
let that = this
event.on('selectedTagCallback', this, function(data) {
// selectedTagCallback: 事件名稱
// data : 回調(diào)的參數(shù)
})
}
組件B觸發(fā)事件
event.emit('selectedTagCallback', data)
組件A銷毀事件
event.remove('selectedTagCallback', this)