Created
September 26, 2017 21:32
-
-
Save AlbinoDrought/605679dcd8d1e4882c208f1e0252d437 to your computer and use it in GitHub Desktop.
Vue mixin for automatic unbinding of element and EventEmitter events
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Ever have this issue? | |
(node) warning: possible EventEmitter memory leak detected. 11 listeners added. Use emitter.setMaxListeners() to increase limit. | |
Swap your bindings in mounted() to: | |
this.bindEvent(serviceInstance, 'foo', () => { | |
console.log('hello world'); | |
}, true); | |
this.bindEvent(serviceInstance, 'bar', (things) => { | |
things.forEach(console.log); | |
}, true); | |
*/ | |
export class EventBinder { | |
constructor() { | |
this.eventListeners = []; | |
} | |
bindEvent(element, name, func, isEventEmitter) { | |
const event = { | |
element, | |
name, | |
func, | |
isEventEmitter, | |
}; | |
if (isEventEmitter) { | |
element.on(name, func); | |
} else { | |
element.addEventListener(name, func); | |
} | |
this.eventListeners.push(event); | |
} | |
unbindEvents() { | |
this.eventListeners.forEach((event) => { | |
const element = event.element; | |
if (event.isEventEmitter) { | |
element.removeListener(event.name, event.func); | |
} else { | |
element.removeEventListener(event.name, event.func); | |
} | |
}); | |
this.eventListeners = []; | |
} | |
} | |
export const autoEventBinderUnbinder = { | |
data() { | |
return { | |
autoEventBinder: new EventBinder(), | |
}; | |
}, | |
methods: { | |
/** | |
* @param {*} element The event emitter to bind to | |
* @param {*} name Name of the event to bind | |
* @param {*} func Your callback function | |
* @param {*} isEventEmitter true ? is EventEmitter : is DOM element | |
*/ | |
bindEvent(element, name, func, isEventEmitter) { | |
this.autoEventBinder.bindEvent(element, name, func, isEventEmitter); | |
}, | |
unbindAllEvents() { | |
this.autoEventBinder.unbindEvents(); | |
}, | |
}, | |
onBeforeDestroy() { | |
this.autoEventBinder.unbindEvents(); | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment