Event.register = function(object) {
// manage a stack of events to invoke
if (!Event.registeredEvents) Event.registeredEvents = $A();
if (!object['initialize']) return;
Event.registeredEvents.push(object);
// if the observer was already created, don't create another one
if (Event.domLoadedObserverCreated) return;
Event.observe(document, 'dom:loaded', function(){
// for each item in the stack, call the initialize method
Event.registeredEvents.each(function(object){
object.initialize();
});
});
Event.domLoadedObserverCreated = true;
};
// Example usage:
var Foo = {
initialize: function(){
// the dom:loaded event has fired
}
};
Event.register(Foo);
var Bar = Class.create({
initialize: function(){
}
};
Bar.initialize = function(){
};
Event.register(Bar);
Some might think that I'm crazy to maintain a custom stack of
dom:loaded events, but it works reliably in all major browsers, fires
events in the order you expect (in all browsers) and isn't susceptible
to event registration failures in IE when a large number of dom:loaded
listeners are created (something I ran into in the past).
Given an object, it will auto-invoke the initialize method. This code
primarily comes from Andrew Dupont, sans the custom event stack.
Advice/suggestions is welcome :)
-justin