1
0
mirror of https://github.com/gorhill/uBlock.git synced 2024-09-04 10:09:38 +02:00

auto cleanup of listeners

This commit is contained in:
gorhill 2015-01-04 10:03:51 -05:00
parent dff1506d85
commit ea2043c0eb

View File

@ -20,7 +20,6 @@
*/
/* exported uDom */
'use strict';
/******************************************************************************/
@ -32,6 +31,8 @@
var uDom = (function() {
'use strict';
/******************************************************************************/
var DOMList = function() {
@ -639,6 +640,24 @@ DOMList.prototype.toggleClasses = function(classNames, targetState) {
/******************************************************************************/
var listenerEntries = [];
var ListenerEntry = function(target, type, capture, callback) {
this.target = target;
this.type = type;
this.capture = capture;
this.callback = callback;
target.addEventListener(type, callback, capture);
};
ListenerEntry.prototype.dispose = function() {
this.target.removeEventListener(this.type, this.callback, this.capture);
this.target = null;
this.callback = null;
};
/******************************************************************************/
var makeEventHandler = function(selector, callback) {
return function(event) {
var dispatcher = event.currentTarget;
@ -662,7 +681,7 @@ DOMList.prototype.on = function(etype, selector, callback) {
var i = this.nodes.length;
while ( i-- ) {
this.nodes[i].addEventListener(etype, callback, selector !== undefined);
listenerEntries.push(new ListenerEntry(this.nodes[i], etype, selector !== undefined, callback));
}
return this;
};
@ -693,6 +712,20 @@ DOMList.prototype.trigger = function(etype) {
/******************************************************************************/
// Cleanup
var onBeforeUnload = function() {
var entry;
while ( entry = listenerEntries.pop() ) {
entry.dispose();
}
window.removeEventListener('beforeunload', onBeforeUnload);
};
window.addEventListener('beforeunload', onBeforeUnload);
/******************************************************************************/
return DOMListFactory;
})();