-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvue-option-events.js
91 lines (83 loc) · 2.19 KB
/
vue-option-events.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import {
isString,
isObject,
isFunction,
each,
} from './lib/utils';
const OPTION_NAME = 'events';
const HANDLER_MAP_NAME = '_eventHandlers';
const INACTIVE_NAME = '_eventInactive';
function offAll(eventBus, vm) {
each(vm[HANDLER_MAP_NAME], (handler, event) => {
eventBus.$off(event, handler);
});
}
const eventBus = {
install(Vue, {
keepAlive = false,
} = {}) {
const originalEmit = Vue.prototype.$emit;
const vue = new Vue();
const strats = Vue.config.optionMergeStrategies;
// use the same methods merging strategy for events
strats[OPTION_NAME] = strats.methods;
// global event bus
each([
'$on',
'$once',
'$off',
'$emit',
], (name) => {
eventBus[name] = vue[name].bind(vue);
});
Vue.prototype.$event = eventBus;
Vue.prototype.$emit = function $emit(event, ...payload) {
originalEmit.call(this, event, ...payload);
if (this != vue) {
originalEmit.call(vue, event, ...payload);
}
};
Vue.mixin({
beforeCreate() {
const vm = this;
if (!isObject(vm.$options[OPTION_NAME])) {
return;
}
const eventHandlers = vm[HANDLER_MAP_NAME] = {};
each(vm.$options[OPTION_NAME], (handler, event) => {
let fn;
if (isFunction(handler)) {
fn = handler;
} else if (isString(handler)) {
fn = vm.$options.methods[handler];
}
if (!isFunction(fn)) {
Vue.util.warn(`handler for event "${event}" is not a function`, vm);
return;
}
eventHandlers[event] = fn.bind(vm);
eventBus.$on(event, eventHandlers[event]);
});
},
activated() {
const vm = this;
if (!keepAlive && vm[INACTIVE_NAME]) {
each(vm[HANDLER_MAP_NAME], (handler, event) => {
eventBus.$on(event, handler);
});
vm[INACTIVE_NAME] = false;
}
},
deactivated() {
if (!keepAlive) {
offAll(eventBus, this);
this[INACTIVE_NAME] = true;
}
},
beforeDestroy() {
offAll(eventBus, this);
},
});
},
};
export default eventBus;