Skip to content

Commit 615aa89

Browse files
committed
fix($rootScope): remove history event handler when app is torn down
Remember the popstate and hashchange handler registered with window when the application bootstraps, and remove it when the application is torn down Closes angular#9897
1 parent 0f7bcfd commit 615aa89

File tree

2 files changed

+18
-5
lines changed

2 files changed

+18
-5
lines changed

src/ng/browser.js

+10-4
Original file line numberDiff line numberDiff line change
@@ -222,10 +222,16 @@ function Browser(window, document, $log, $sniffer) {
222222
var urlChangeListeners = [],
223223
urlChangeInit = false;
224224

225-
function cacheStateAndFireUrlChange() {
225+
/**
226+
* @private
227+
* Event handler for hashchange and popstate events.
228+
* Note: this method is used only by $rootScope to remove the handler when an app
229+
* is torn down. (See https://github.com/angular/angular.js/issues/9897)
230+
*/
231+
self.cacheStateAndFireUrlChange = function() {
226232
cacheState();
227233
fireUrlChange();
228-
}
234+
};
229235

230236
// This variable should be used *only* inside the cacheState function.
231237
var lastCachedState = null;
@@ -282,9 +288,9 @@ function Browser(window, document, $log, $sniffer) {
282288
// changed by push/replaceState
283289

284290
// html5 history api - popstate event
285-
if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
291+
if ($sniffer.history) jqLite(window).on('popstate', self.cacheStateAndFireUrlChange);
286292
// hashchange event
287-
jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
293+
jqLite(window).on('hashchange', self.cacheStateAndFireUrlChange);
288294

289295
urlChangeInit = true;
290296
}

src/ng/rootScope.js

+8-1
Original file line numberDiff line numberDiff line change
@@ -861,7 +861,14 @@ function $RootScopeProvider() {
861861

862862
this.$broadcast('$destroy');
863863
this.$$destroyed = true;
864-
if (this === $rootScope) return;
864+
865+
if (this === $rootScope) {
866+
//Remove handlers attached to window when $rootScope is removed
867+
//See https://github.com/angular/angular.js/issues/9897
868+
jqLite(window).unbind("popstate", $browser.cacheStateAndFireUrlChange);
869+
jqLite(window).unbind("hashchange", $browser.cacheStateAndFireUrlChange);
870+
return;
871+
}
865872

866873
for (var eventName in this.$$listenerCount) {
867874
decrementListenerCount(this, this.$$listenerCount[eventName], eventName);

0 commit comments

Comments
 (0)