Created
September 21, 2018 10:35
-
-
Save oddvalue/be622a334491b717a9f037f861da44f8 to your computer and use it in GitHub Desktop.
Performant window resize event listener
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
/** | |
* Performant window resize event listener | |
* @return {object} | |
* | |
* @usage | |
* import windowResize from './window-resize'; | |
* windowResize.listen(() => { | |
* ... | |
* }); | |
*/ | |
export default (() => { | |
const windowResize = { | |
callbacks: [], | |
running: false, | |
/** | |
* Add the event listener | |
* @return {undefinied} | |
*/ | |
init() { | |
window.addEventListener('resize', windowResize.resize, { passive: true }); | |
}, | |
/** | |
* Loop through callbacks and run them | |
* @return {undefinied} | |
*/ | |
runCallbacks() { | |
windowResize.callbacks.forEach((callback) => { | |
callback(); | |
}); | |
windowResize.running = false; | |
}, | |
/** | |
* Event listener method | |
* @return {undefinied} | |
*/ | |
resize() { | |
if (!windowResize.running) { | |
windowResize.running = true; | |
if (window.requestAnimationFrame) { | |
window.requestAnimationFrame(() => windowResize.runCallbacks()); | |
} else { | |
setTimeout(() => windowResize.runCallbacks(), 100); | |
} | |
} | |
}, | |
/** | |
* Add a callback to the callbacks array | |
* @return {undefinied} | |
*/ | |
addCallback(callback) { | |
if (callback) { | |
windowResize.callbacks.push(callback); | |
} | |
}, | |
/** | |
* Test whether or not any callbacks have been registered yet | |
* @return {Boolean} | |
*/ | |
hasCallbacks() { | |
return windowResize.callbacks.length > 0; | |
}, | |
}; | |
return { | |
// public method to add additional callback | |
listen: (callback) => { | |
if (!windowResize.hasCallbacks()) { | |
windowResize.init(); | |
} | |
windowResize.addCallback(callback); | |
}, | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment