Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Last active December 21, 2020 05:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfkaye/ef0e3ff2c0f6448bb30c6ff70c605aa6 to your computer and use it in GitHub Desktop.
Save dfkaye/ef0e3ff2c0f6448bb30c6ff70c605aa6 to your computer and use it in GitHub Desktop.
defer dom init handlers using readyState checks
// 27 May 2020
// pulled from the SAM pattern calculator codepen
// https://codepen.io/dfkaye/pen/QWjdEZe
// 24 June 2020 - support both event() and event.handleEvent() interfaces.
// 4 December 2020 - added to SAM pattern boilerplate
// see https://gist.github.com/dfkaye/8c3579662a344f65777153251bb0b5a7/
// 5 December 2020 - rename schedule as defer, run as exec.
// Enables us to call view.init() multiple times, even after document is ready.
var view = (function() {
function register(handler) {
if (typeof handler != 'function' && typeof handler.handleEvent != "function") {
return;
}
var onReadyStateChange = function onReadyStateChange() {
if (document.readyState == "complete") {
exec(handler);
return true
}
}
onReadyStateChange() || (
document.addEventListener('readystatechange', onReadyStateChange, { once: true })
)
}
function exec(handler) {
typeof handler.handleEvent == "function"
? handler.handleEvent.call(handler)
: typeof handler == "function"
? handler.call(document)
: 0;
}
var api = {
init(handler) {
// Enables us to call init() multiple times, even after document is ready.
register(handler)
},
handlers: {
onclick: (e) => { console.log("click", e) },
onkeydown: (e) => { console.log("keydown", e) }
}
};
return api;
}());
var action = (function () {
var api = {
next({ action, value }) {
console.warn({ action, value });
}
};
return api;
}());
view.init(function() {
console.log('1st init');
document.addEventListener('click', view.handlers.onclick);
document.addEventListener('keydown', view.handlers.onkeydown);
action.next({ action: 'reset', value: '' });
// Prove init runs after DOM loaded
view.init(function() {
console.log('2nd init');
});
});
// handleEvent interface 24 June 2020
view.init({ handleEvent: function(e) {
console.log('handleEvent', e);
}});
document.body.click()
// Should see in console:
// 1st init
// {action: "reset", value: ""}
// 2nd init
// handleEvent undefined
// click > MouseEvent
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment