Fix generic event handler and $events expando removal for IE
[jquery.git] / src / event / event.js
index 4a63316..e0d4b90 100644 (file)
@@ -22,16 +22,16 @@ jQuery.event = {
                        handler.guid = this.guid++;
 
                // Init the element's event structure
-               if (!element.events)
-                       element.events = {};
+               if (!element.$events)
+                       element.$events = {};
 
                // Get the current list of functions bound to this event
-               var handlers = element.events[type];
+               var handlers = element.$events[type];
 
                // If it hasn't been initialized yet
                if (!handlers) {
                        // Init the event handler queue
-                       handlers = element.events[type] = {};
+                       handlers = element.$events[type] = {};
 
                        // Remember an existing handler, if it's already there
                        if (element["on" + type])
@@ -55,47 +55,79 @@ jQuery.event = {
 
        // Detach an event or set of events from an element
        remove: function(element, type, handler) {
-               if (element.events)
-                       if ( type && type.type )
-                               delete element.events[ type.type ][ type.handler.guid ];
-                       else if (type && element.events[type])
+               var events = element.$events, ret;
+
+               if ( events ) {
+                       // type is actually an event object here
+                       if ( type && type.type ) {
+                               handler = type.handler;
+                               type = type.type;
+                       }
+                       
+                       if ( !type ) {
+                               for ( type in events )
+                                       this.remove( element, type );
+
+                       } else if ( events[type] ) {
+                               // remove the given handler for the given type
                                if ( handler )
-                                       delete element.events[type][handler.guid];
+                                       delete events[type][handler.guid];
+                               
+                               // remove all handlers for the given type
                                else
-                                       for ( var i in element.events[type] )
-                                               delete element.events[type][i];
-                       else
-                               for ( var j in element.events )
-                                       this.remove( element, j );
+                                       for ( handler in element.$events[type] )
+                                               delete events[type][handler];
+
+                               // remove generic event handler if no more handlers exist
+                               for ( ret in events[type] ) break;
+                               if ( !ret ) {
+                                       ret = element["on" + type] = null;
+                                       delete events[type];
+                               }
+                       }
+
+                       // Remove the expando if it's no longer used
+                       for ( ret in events ) break;
+                       if ( !ret )
+                               element.$events = null;
+               }
        },
 
-       trigger: function(type,data,element) {
+       trigger: function(type, data, element) {
                // Clone the incoming data, if any
                data = jQuery.makeArray(data || []);
 
                // Handle a global trigger
-               if ( !element ) {
-                       var g = this.global[type];
-                       if ( g )
-                               for ( var i = 0, gl = g.length; i < gl; i++ )
-                                       this.trigger( type, data, g[i] );
+               if ( !element )
+                       jQuery.each( this.global[type] || [], function(){
+                               jQuery.event.trigger( type, data, this );
+                       });
 
                // Handle triggering a single element
-               } else if ( element["on" + type] ) {
-                       if ( element[ type ] && element[ type ].constructor == Function )
-                               element[ type ]();
-                       else {
+               else {
+                       var handler = element["on" + type ], val,
+                               fn = jQuery.isFunction( element[ type ] );
+
+                       if ( handler ) {
                                // Pass along a fake event
                                data.unshift( this.fix({ type: type, target: element }) );
        
                                // Trigger the event
-                               element["on" + type].apply( element, data );
+                               if ( (val = handler.apply( element, data )) !== false )
+                                       this.triggered = true;
                        }
+
+                       if ( fn && val !== false )
+                               element[ type ]();
+
+                       this.triggered = false;
                }
        },
 
        handle: function(event) {
-               if ( typeof jQuery == "undefined" ) return false;
+               // Handle the second event of a trigger and when
+               // an event is called after a page has unloaded
+               if ( typeof jQuery == "undefined" || jQuery.event.triggered ) return;
 
                // Empty object is for triggered events with no data
                event = jQuery.event.fix( event || window.event || {} ); 
@@ -103,7 +135,7 @@ jQuery.event = {
                // returned undefined or false
                var returnValue;
 
-               var c = this.events[event.type];
+               var c = this.$events[event.type];
 
                var args = [].slice.call( arguments, 1 );
                args.unshift( event );
@@ -133,7 +165,7 @@ jQuery.event = {
                        event.target = event.srcElement;
 
                // Calculate pageX/Y if missing and clientX/Y available
-               if ( typeof event.pageX == "undefined" && typeof event.clientX != "undefined" ) {
+               if ( event.pageX == undefined && event.clientX != undefined ) {
                        var e = document.documentElement, b = document.body;
                        event.pageX = event.clientX + (e.scrollLeft || b.scrollLeft);
                        event.pageY = event.clientY + (e.scrollTop || b.scrollTop);
@@ -184,7 +216,7 @@ jQuery.fn.extend({
         *
         * In most cases, you can define your event handlers as anonymous functions
         * (see first example). In cases where that is not possible, you can pass additional
-        * data as the second paramter (and the handler function as the third), see 
+        * data as the second parameter (and the handler function as the third), see 
         * second example.
         *
         * @example $("p").bind("click", function(){
@@ -299,15 +331,35 @@ jQuery.fn.extend({
        },
 
        /**
-        * Trigger a type of event on every matched element.
+        * Trigger a type of event on every matched element. This will also cause
+        * the default action of the browser with the same name (if one exists)
+        * to be executed. For example, passing 'submit' to the trigger()
+        * function will also cause the browser to submit the form. This
+        * default action can be prevented by returning false from one of
+        * the functions bound to the event.
+        *
+        * You can also trigger custom events registered with bind.
         *
         * @example $("p").trigger("click")
         * @before <p click="alert('hello')">Hello</p>
         * @result alert('hello')
         *
+        * @example $("p").click(function(event, a, b) {
+        *   // when a normal click fires, a and b are undefined
+        *   // for a trigger like below a refers too "foo" and b refers to "bar"
+        * }).trigger("click", ["foo", "bar"]);
+        * @desc Example of how to pass arbitrary data to an event
+        * 
+        * @example $("p").bind("myEvent",function(event,message1,message2) {
+        *      alert(message1 + ' ' + message2);
+        * });
+        * $("p").trigger("myEvent",["Hello","World"]);
+        * @result alert('Hello World') // One for each paragraph
+        *
         * @name trigger
         * @type jQuery
         * @param String type An event type to trigger.
+        * @param Array data (optional) Additional data to pass as arguments (after the event object) to the event handler
         * @cat Events
         */
        trigger: function( type, data ) {
@@ -366,9 +418,9 @@ jQuery.fn.extend({
         * (a common error in using a mouseout event handler).
         *
         * @example $("p").hover(function(){
-        *   $(this).addClass("over");
+        *   $(this).addClass("hover");
         * },function(){
-        *   $(this).addClass("out");
+        *   $(this).removeClass("hover");
         * });
         *
         * @name hover
@@ -405,9 +457,13 @@ jQuery.fn.extend({
         * the response times of your web applications.
         *
         * In a nutshell, this is a solid replacement for using window.onload, 
-        * and attaching a function to that. By using this method, your bound Function 
+        * and attaching a function to that. By using this method, your bound function 
         * will be called the instant the DOM is ready to be read and manipulated, 
-        * which is exactly what 99.99% of all Javascript code needs to run.
+        * which is when what 99.99% of all JavaScript code needs to run.
+        *
+        * There is one argument passed to the ready event handler: A reference to
+        * the jQuery function. You can name that argument whatever you like, and
+        * can therefore stick with the $ alias without risk of naming collisions.
         * 
         * Please ensure you have no code in your &lt;body&gt; onload event handler, 
         * otherwise $(document).ready() may not fire.
@@ -417,21 +473,30 @@ jQuery.fn.extend({
         *
         * @example $(document).ready(function(){ Your code here... });
         *
+        * @example jQuery(function($) {
+        *   // Your code using failsafe $ alias here...
+        * });
+        * @desc Uses both the [[Core#.24.28_fn_.29|shortcut]] for $(document).ready() and the argument
+        * to write failsafe jQuery code using the $ alias, without relying on the
+        * global alias.
+        *
         * @name ready
         * @type jQuery
         * @param Function fn The function to be executed when the DOM is ready.
         * @cat Events
+        * @see $.noConflict()
+        * @see $(Function)
         */
        ready: function(f) {
                // If the DOM is already ready
                if ( jQuery.isReady )
                        // Execute the function immediately
-                       f.apply( document );
+                       f.apply( document, [jQuery] );
                        
                // Otherwise, remember the function for later
                else {
                        // Add the function to the wait list
-                       jQuery.readyList.push( f );
+                       jQuery.readyList.push( function() { return f.apply(this, [jQuery]) } );
                }
        
                return this;
@@ -455,8 +520,9 @@ jQuery.extend({
                        // If there are functions bound, to execute
                        if ( jQuery.readyList ) {
                                // Execute all of them
-                               for ( var i = 0; i < jQuery.readyList.length; i++ )
-                                       jQuery.readyList[i].apply( document );
+                               jQuery.each( jQuery.readyList, function(){
+                                       this.apply( document );
+                               });
                                
                                // Reset the list of functions
                                jQuery.readyList = null;
@@ -500,13 +566,15 @@ new function(){
 
        /**
         * Trigger the submit event of each matched element. This causes all of the functions
-        * that have been bound to thet submit event to be executed.
+        * that have been bound to that submit event to be executed, and calls the browser's
+        * default submit action on the matching element(s). This default action can be prevented
+        * by returning false from one of the functions bound to the submit event.
         *
         * Note: This does not execute the submit method of the form element! If you need to
         * submit the form via code, you have to use the DOM method, eg. $("form")[0].submit();
         *
         * @example $("form").submit();
-        * @desc Triggers all submit events registered for forms, but does not submit the form
+        * @desc Triggers all submit events registered to the matched form(s), and submits them.
         *
         * @name submit
         * @type jQuery
@@ -609,7 +677,9 @@ new function(){
 
        /**
         * Trigger the blur event of each matched element. This causes all of the functions
-        * that have been bound to thet blur event to be executed.
+        * that have been bound to that blur event to be executed, and calls the browser's
+        * default blur action on the matching element(s). This default action can be prevented
+        * by returning false from one of the functions bound to the blur event.
         *
         * Note: This does not execute the blur method of the underlying elements! If you need to
         * blur an element via code, you have to use the DOM method, eg. $("#myinput")[0].blur();
@@ -651,7 +721,9 @@ new function(){
 
        /**
         * Trigger the select event of each matched element. This causes all of the functions
-        * that have been bound to thet select event to be executed.
+        * that have been bound to that select event to be executed, and calls the browser's
+        * default select action on the matching element(s). This default action can be prevented
+        * by returning false from one of the functions bound to the select event.
         *
         * @example $("p").select();
         * @before <p onselect="alert('Hello');">Hello</p>