-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
55 additions
and
13 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
type RouteListenerFunc = (url: string) => void; | ||
|
||
class RouteListener { | ||
private listening: boolean = false; | ||
private listeners: Array<RouteListenerFunc> = []; | ||
|
||
addListener(listener: RouteListenerFunc): void { | ||
this.listeners.push(listener); | ||
|
||
if (!this.listening) { | ||
this.listening = true; | ||
this.startListen(); | ||
|
||
setTimeout(() => this.notifyListeners(window.location.pathname)) // Initial notification | ||
} | ||
} | ||
|
||
private startListen() { | ||
// Overriding the pushState method to notify listeners | ||
const pushState = window.history.pushState; | ||
window.history.pushState = (...args): void => { | ||
pushState.apply(window.history, args); | ||
|
||
const url = args[2]; | ||
if (!url) { | ||
return; | ||
} else if (url instanceof URL) { | ||
this.notifyListeners(url.toString()); | ||
} else { | ||
this.notifyListeners(url); | ||
} | ||
}; | ||
} | ||
|
||
private notifyListeners(url: string): void { | ||
for (const listener of this.listeners) { | ||
// Scheduled for the next event loop | ||
setTimeout(() => listener(url)); | ||
} | ||
} | ||
|
||
removeListener(listener: Function): void { | ||
this.listeners = this.listeners.filter(l => l !== listener); | ||
} | ||
} | ||
|
||
export { RouteListener, RouteListenerFunc }; |
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