Emulate domready event with a custom event (mootools)
- by Rob
I need to fire a one time only custom event that functions like the domready event, in that if new events are added after the event has occurred they are fired immediately.
This is for some code that cannot execute until certain data and resources are initialized, so I want to do something like this:
// I am including a script (loadResources.js) to load data and other resources,
// when loadResources.js is done doing it's thing it will fire resourcesAreLoaded with:
window.fireEvent('resourcesAreLoaded');
window.addEvent('resourcesAreLoaded', function() {
// this is fine
});
$('mybutton').addEvent('click', function() {
window.addEvent('resourcesAreLoaded', function() {
// this is not fine, because resourcesAreLoaded has already fired
// by the time the button is clicked
});
});
If possible I would like resourcesAreLoaded to function like domready, and execute the code immediately if the event has already fired:
window.addEvent('testIsReady', function() {
alert('firing test');
});
window.fireEvent('testIsReady');
window.addEvent('test', function() {
// this will never execute unless I call fireEvent('testIsReady') again
alert('test 2');
});
window.addEvent('domready', function() {
alert('domready is firing');
});
window.addEvent('domready', function() {
setTimeout(function() {
alert('domready has already fired, so this is executed immediately');
}, 500);
});