Skip to content

Instantly share code, notes, and snippets.

@abriening
Created October 22, 2009 19:44
Show Gist options
  • Save abriening/216228 to your computer and use it in GitHub Desktop.
Save abriening/216228 to your computer and use it in GitHub Desktop.
/*
* Extend the Event Object
*
* ready_dom: add functions to run on DOMContentLoaded
*
* ready_ajax: add functions to run after Ajax onComplete responses
*
* ready: add functions to run on both ready_dom & ready_ajax. These should
* be constructed so that running more than once will not have any
* side-effects.
*
* delegate: add event listeners for "bubbling" events. These functions will always have
* "document" as the event.currentTarget and checks the event.target and ancestors to see if it
* matches the supplied html +selector+. Any function that returns false will stop all further
* listeners from executing. The event.stopPropagaion does not have any effect since all listeners
* are applied to the "document" root.
*
* supported events: click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, keydown, keypress, keyup
* unsupported events: blur, focus, mouseenter, mouseleave, change, submit ( as these do not "bubble" )
*
* see: http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-flow-bubbling
*
*/
Object.extend( Event, {
ready: function(func){
Event.ready_dom(func);
Event.ready_ajax(func);
},
ready_dom: function(func){
Element.observe(document, 'dom:loaded', func);
},
ready_ajax: function(func){
Ajax.Responders.register({ onComplete: func });
},
delegate: function(selector, event_type, func){
Element.observe(document, event_type, function(event){
if( !event.stopped && ( element = event.findElement(selector) ) ){
var ret = func.apply(element, [event]);
if(ret === false){ event.stop(); }
return ret;
}
})
}
});
/*
* This is similar to Event.ready_dom except you can pass
* function references.
* add_load_function( some_global_function );
* Event.ready_dom functions will have the "document" sent as the first parameter.
*/
var add_load_function = function(func){
Event.ready_dom(function(){func()});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment