|
| 1 | +/** |
| 2 | + * Plugin class. |
| 3 | + */ |
| 4 | + |
| 5 | +import EventManager from './EventManager'; |
| 6 | +import Util, {log, assign, forEach, isArray, isObject} from './util'; |
| 7 | + |
| 8 | +const Events = new EventManager(); |
| 9 | + |
| 10 | +export default { |
| 11 | + |
| 12 | + version: '__VERSION__', |
| 13 | + |
| 14 | + install(Vue, options = {}) { |
| 15 | + |
| 16 | + if (this.installed) { |
| 17 | + return; |
| 18 | + } |
| 19 | + |
| 20 | + Util(Vue); log(this.version); |
| 21 | + |
| 22 | + // add global instance/methods |
| 23 | + Vue.prototype.$events = Vue.events = assign(Events, options); |
| 24 | + Vue.prototype.$trigger = function (event, params = [], asynch = false) { |
| 25 | + |
| 26 | + if (!isObject(event)) { |
| 27 | + event = {name: event, origin: this}; |
| 28 | + } |
| 29 | + |
| 30 | + return Events.trigger(event, params, asynch); |
| 31 | + }; |
| 32 | + |
| 33 | + // add merge strategy for "events" |
| 34 | + Vue.config.optionMergeStrategies.events = mergeEvents; |
| 35 | + |
| 36 | + // add mixin to parse "events" from component options |
| 37 | + Vue.mixin({beforeCreate: initEvents}); |
| 38 | + } |
| 39 | + |
| 40 | +}; |
| 41 | + |
| 42 | +export function mergeEvents(parentVal, childVal) { |
| 43 | + |
| 44 | + if (!childVal) { |
| 45 | + return parentVal; |
| 46 | + } |
| 47 | + |
| 48 | + if (!parentVal) { |
| 49 | + return childVal; |
| 50 | + } |
| 51 | + |
| 52 | + const events = assign({}, parentVal); |
| 53 | + |
| 54 | + for (const event in childVal) { |
| 55 | + |
| 56 | + let parent = events[event]; |
| 57 | + const child = childVal[event]; |
| 58 | + |
| 59 | + if (parent && !isArray(parent)) { |
| 60 | + parent = [parent]; |
| 61 | + } |
| 62 | + |
| 63 | + events[event] = parent |
| 64 | + ? parent.concat(child) |
| 65 | + : isArray(child) ? child : [child]; |
| 66 | + } |
| 67 | + |
| 68 | + return events; |
| 69 | +} |
| 70 | + |
| 71 | +export function initEvents() { |
| 72 | + |
| 73 | + const _events = []; |
| 74 | + const {events} = this.$options; |
| 75 | + |
| 76 | + if (events) { |
| 77 | + |
| 78 | + forEach(events, (listeners, event) => { |
| 79 | + forEach(isArray(listeners) ? listeners : [listeners], listener => { |
| 80 | + |
| 81 | + let priority = 0; |
| 82 | + |
| 83 | + if (isObject(listener)) { |
| 84 | + priority = listener.priority; |
| 85 | + listener = listener.handler; |
| 86 | + } |
| 87 | + |
| 88 | + _events.push(this.$events.on(event, bindListener(listener, this), priority)); |
| 89 | + }); |
| 90 | + }); |
| 91 | + |
| 92 | + this.$on('hook:beforeDestroy', () => _events.forEach(off => off())); |
| 93 | + } |
| 94 | +} |
| 95 | + |
| 96 | +export function bindListener(fn, vm) { |
| 97 | + |
| 98 | + if (typeof fn === 'string') { |
| 99 | + return function () { |
| 100 | + return vm[fn].apply(vm, arguments); |
| 101 | + }; |
| 102 | + } |
| 103 | + |
| 104 | + return fn.bind(vm); |
| 105 | +} |
0 commit comments