Last active
April 7, 2020 23:05
-
-
Save ricealexander/fe0a67d659caee15f560760e7234b612 to your computer and use it in GitHub Desktop.
SPA can load custom scripts. We do not have control of the SPA otherwise. These files can isolate recurring code so it does not persist from page to page
This file contains hidden or 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
(function() { | |
// Isolate Event Listener so it is safe to use | |
// current URL is checked each time the event listener is activated | |
// if a different page is loaded, the event will destroy itself the next time it is active | |
// In this demo, we are able to completely isolate this behavior inside | |
// an abstraction called createIsolatedEvent, which is fully reusable | |
// createIsolatedEvent abstraction | |
function createIsolatedEvent (element, type, callback) { | |
function currentPage () { return window.location.pathname } | |
var startingPage = currentPage() | |
function isolatedCallback(event) { | |
var hasChangedPages = (startingPage !== currentPage()) | |
if (hasChangedPages) { | |
element.removeEventListener(type, isolatedCallback) | |
return | |
} | |
return callback(event) | |
} | |
element.addEventListener(type, isolatedCallback) | |
} | |
// Example Usage | |
function handleClick (event) { | |
console.log(event.target) | |
} | |
createIsolatedEvent(window, 'click', handleClick) // abstraction of window.addEventListener('click', handleClick) | |
})() |
This file contains hidden or 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
(function() { | |
// setIsolatedInterval | |
// an alternative to the isolateInterval code | |
// which wraps all of the interval functionality in an abstraction | |
// setIsolatedInterval can be used as an alternative to setInterval | |
// with all the termination logic built inside | |
function setIsolatedInterval (callback, milliseconds) { | |
function currentPage () { return window.location.pathname } | |
var startingPage = currentPage() | |
var interval | |
function isolatedCallback () { | |
var hasChangedPages = (startingPage !== currentPage()) | |
if (hasChangedPages) { | |
clearInterval(interval) | |
return | |
} | |
return callback() | |
} | |
interval = setInterval(isolatedCallback, milliseconds) | |
return interval | |
} | |
// Example Usage | |
function doSomethingRepeatedly () { | |
console.log('Running isolated interval') | |
} | |
setIsolatedInterval(doSomethingRepeatedly, 1000) // abstraction of setInterval(doSomethingRepeatedly, 1000) | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment