From ea2043c0eb2fad05d05f3dfecfa76c868030099a Mon Sep 17 00:00:00 2001 From: gorhill Date: Sun, 4 Jan 2015 10:03:51 -0500 Subject: [PATCH] auto cleanup of listeners --- src/js/udom.js | 37 +++++++++++++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/src/js/udom.js b/src/js/udom.js index 1d90f865d..0ff92e483 100644 --- a/src/js/udom.js +++ b/src/js/udom.js @@ -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; })();