Emulate domready event with a custom event (mootools)
Posted
by Rob
on Stack Overflow
See other posts from Stack Overflow
or by Rob
Published on 2010-05-06T19:43:32Z
Indexed on
2010/05/06
19:48 UTC
Read the original article
Hit count: 385
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);
});
© Stack Overflow or respective owner