fix for #4189, live/die now work with contexts other than just document
[jquery.git] / src / event.js
index 73a6eac..e5f6a45 100644 (file)
@@ -26,10 +26,7 @@ jQuery.event = {
                        var fn = handler;
 
                        // Create unique handler function, wrapped around original handler
-                       handler = this.proxy( fn, function() {
-                               // Pass arguments and context to original handler
-                               return fn.apply(this, arguments);
-                       });
+                       handler = this.proxy( fn );
 
                        // Store data in unique handler
                        handler.data = data;
@@ -119,7 +116,7 @@ jQuery.event = {
                                        // Namespaced event handlers
                                        var namespaces = type.split(".");
                                        type = namespaces.shift();
-                                       var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");
+                                       var namespace = new RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");
 
                                        if ( events[type] ) {
                                                // remove the given handler for the given type
@@ -128,10 +125,10 @@ jQuery.event = {
 
                                                // remove all handlers for the given type
                                                else
-                                                       for ( handler in events[type] )
+                                                       for ( var handle in events[type] )
                                                                // Handle the removal of namespaced events
-                                                               if ( namespace.test(events[type][handler].type) )
-                                                                       delete events[type][handler];
+                                                               if ( namespace.test(events[type][handle].type) )
+                                                                       delete events[type][handle];
                                                                        
                                                if ( jQuery.event.specialAll[type] )
                                                        jQuery.event.specialAll[type].teardown.call(elem, namespaces);
@@ -163,103 +160,88 @@ jQuery.event = {
                }
        },
 
-       trigger: function(type, data, elem, donative, extra, dohandlers) {
-               // Clone the incoming data, if any
-               data = jQuery.makeArray(data);
+       // bubbling is internal
+       trigger: function( event, data, elem, bubbling ) {
+               // Event object or event type
+               var type = event.type || event;
+
+               if( !bubbling ){
+                       event = typeof event === "object" ?
+                               // jQuery.Event object
+                               event[expando] ? event :
+                               // Object literal
+                               jQuery.extend( jQuery.Event(type), event ) :
+                               // Just the event type (string)
+                               jQuery.Event(type);
+
+                       if ( type.indexOf("!") >= 0 ) {
+                               event.type = type = type.slice(0, -1);
+                               event.exclusive = true;
+                       }
 
-               if ( type.indexOf("!") >= 0 ) {
-                       type = type.slice(0, -1);
-                       var exclusive = true;
-               }
+                       // Handle a global trigger
+                       if ( !elem ) {
+                               // Don't bubble custom events when global (to avoid too much overhead)
+                               event.stopPropagation();
+                               // Only trigger if we've ever bound an event for it
+                               if ( this.global[type] )
+                                       jQuery.each( jQuery.cache, function(){
+                                               if ( this.events && this.events[type] )
+                                                       jQuery.event.trigger( event, data, this.handle.elem );
+                                       });
+                       }
 
-               // Handle a global trigger
-               if ( !elem ) {
-                       // Only trigger if we've ever bound an event for it
-                       if ( this.global[type] )
-                               jQuery.each( jQuery.cache, function(){
-                                       if ( this.events && this.events[type] )
-                                               jQuery.event.trigger( type, data, this.handle.elem );
-                               });
+                       // Handle triggering a single element
 
-               // Handle triggering a single element
-               } else {
                        // don't do events on text and comment nodes
-                       if ( elem.nodeType == 3 || elem.nodeType == 8 )
+                       if ( !elem || elem.nodeType == 3 || elem.nodeType == 8 )
                                return undefined;
+                       
+                       // Clean up in case it is reused
+                       event.result = undefined;
+                       event.target = elem;
+                       
+                       // Clone the incoming data, if any
+                       data = jQuery.makeArray(data);
+                       data.unshift( event );
+               }
 
-                       var val, ret, fn = jQuery.isFunction( elem[ type ] || null ),
-                               // Check to see if we need to provide a fake event, or not
-                               event = !data[0] || !data[0].preventDefault;
-
-                       // Pass along a fake event
-                       if ( event ) {
-                               data.unshift({
-                                       type: type,
-                                       target: elem,
-                                       preventDefault: function(){},
-                                       stopPropagation: function(){},
-                                       stopImmediatePropagation:stopImmediatePropagation,
-                                       timeStamp: now()
-                               });
-                               data[0][expando] = true; // no need to fix fake event
-                       }
-
-                       // Enforce the right trigger type
-                       data[0].type = type;
-                       if ( exclusive )
-                               data[0].exclusive = true;
-
-                       if ( dohandlers !== false ) {
-                               // Trigger the event, it is assumed that "handle" is a function
-                               var handle = jQuery.data(elem, "handle");
-                               if ( handle )
-                                       val = handle.apply( elem, data );
+               event.currentTarget = elem;
 
-                               // Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
-                               if ( (!fn || (jQuery.nodeName(elem, 'a') && type == "click")) && elem["on"+type] && elem["on"+type].apply( elem, data ) === false )
-                                       val = false;
-                       }
+               // Trigger the event, it is assumed that "handle" is a function
+               var handle = jQuery.data(elem, "handle");
+               if ( handle )
+                       handle.apply( elem, data );
 
-                       if ( donative !== false && val !== false ) {
-                               var parent = elem.parentNode || elem.ownerDocument;
-                               if ( parent )
-                                       jQuery.event.trigger(type, data, parent, donative);
-                       }
+               // Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
+               if ( (!elem[type] || (jQuery.nodeName(elem, 'a') && type == "click")) && elem["on"+type] && elem["on"+type].apply( elem, data ) === false )
+                       event.result = false;
 
-                       // Extra functions don't get the custom event object
-                       if ( event )
-                               data.shift();
-
-                       // Handle triggering of extra function
-                       if ( extra && jQuery.isFunction( extra ) ) {
-                               // call the extra function and tack the current return value on the end for possible inspection
-                               ret = extra.apply( elem, val == null ? data : data.concat( val ) );
-                               // if anything is returned, give it precedence and have it overwrite the previous value
-                               if ( ret !== undefined )
-                                       val = ret;
-                       }
+               // Trigger the native events (except for clicks on links)
+               if ( !bubbling && elem[type] && !event.isDefaultPrevented() && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
+                       this.triggered = true;
+                       try {
+                               elem[ type ]();
+                       // prevent IE from throwing an error for some hidden elements
+                       } catch (e) {}
+               }
 
-                       // Trigger the native events (except for clicks on links)
-                       if ( fn && donative !== false && val !== false && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
-                               this.triggered = true;
-                               try {
-                                       elem[ type ]();
-                               // prevent IE from throwing an error for some hidden elements
-                               } catch (e) {}
-                       }
+               this.triggered = false;
 
-                       this.triggered = false;
+               if ( !event.isPropagationStopped() ) {
+                       var parent = elem.parentNode || elem.ownerDocument;
+                       if ( parent )
+                               jQuery.event.trigger(event, data, parent, true);
                }
-
-               return val;
        },
 
        handle: function(event) {
                // returned undefined or false
-               var val, ret, all, handlers;
+               var all, handlers;
 
                event = arguments[0] = jQuery.event.fix( event || window.event );
-
+               event.currentTarget = this;
+               
                // Namespaced event handlers
                var namespaces = event.type.split(".");
                event.type = namespaces.shift();
@@ -267,7 +249,7 @@ jQuery.event = {
                // Cache this now, all = true means, any handler
                all = !namespaces.length && !event.exclusive;
                
-               var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");
+               var namespace = new RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");
 
                handlers = ( jQuery.data(this, "events") || {} )[event.type];
 
@@ -281,26 +263,24 @@ jQuery.event = {
                                event.handler = handler;
                                event.data = handler.data;
 
-                               ret = handler.apply( this, arguments );
-
-                               if ( val !== false )
-                                       val = ret;
+                               var ret = handler.apply(this, arguments);
 
-                               if ( ret === false ) {
-                                       event.preventDefault();
-                                       event.stopPropagation();
+                               if( ret !== undefined ){
+                                       event.result = ret;
+                                       if ( ret === false ) {
+                                               event.preventDefault();
+                                               event.stopPropagation();
+                                       }
                                }
 
-                               if( event._sip )
+                               if( event.isImmediatePropagationStopped() )
                                        break;
 
                        }
                }
-
-               return val;
        },
 
-       props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target timeStamp toElement type view wheelDelta which".split(" "),
+       props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
 
        fix: function(event) {
                if ( event[expando] )
@@ -309,38 +289,13 @@ jQuery.event = {
                // store a copy of the original event object
                // and "clone" to set read-only properties
                var originalEvent = event;
-               event = { originalEvent: originalEvent };
+               event = jQuery.Event( originalEvent );
 
                for ( var i = this.props.length, prop; i; ){
                        prop = this.props[ --i ];
                        event[ prop ] = originalEvent[ prop ];
                }
 
-               // Mark it as fixed
-               event[expando] = true;
-
-               // add preventDefault and stopPropagation since
-               // they will not work on the clone
-               event.preventDefault = function() {
-                       // if preventDefault exists run it on the original event
-                       if (originalEvent.preventDefault)
-                               originalEvent.preventDefault();
-                       // otherwise set the returnValue property of the original event to false (IE)
-                       originalEvent.returnValue = false;
-               };
-               event.stopPropagation = function() {
-                       // if stopPropagation exists run it on the original event
-                       if (originalEvent.stopPropagation)
-                               originalEvent.stopPropagation();
-                       // otherwise set the cancelBubble property of the original event to true (IE)
-                       originalEvent.cancelBubble = true;
-               };
-
-               event.stopImmediatePropagation = stopImmediatePropagation;
-
-               // Fix timeStamp
-               event.timeStamp = event.timeStamp || now();
-
                // Fix target property, if necessary
                if ( !event.target )
                        event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either
@@ -377,6 +332,7 @@ jQuery.event = {
        },
 
        proxy: function( fn, proxy ){
+               proxy = proxy || function(){ return fn.apply(this, arguments); };
                // Set the guid of unique handler to the same of original handler, so it can be removed
                proxy.guid = fn.guid = fn.guid || proxy.guid || this.guid++;
                // So proxy can be declared as an argument
@@ -398,14 +354,14 @@ jQuery.event = {
                        },
                        teardown:  function( namespaces ){
                                if ( namespaces.length ) {
-                                       var remove = 0, name = RegExp("(^|\\.)" + namespaces[0] + "(\\.|$)");
+                                       var remove = 0, name = new RegExp("(^|\\.)" + namespaces[0] + "(\\.|$)");
                                        
                                        jQuery.each( (jQuery.data(this, "events").live || {}), function(){
                                                if ( name.test(this.type) )
                                                        remove++;
                                        });
                                        
-                                       if ( remove <= 1 )
+                                       if ( remove < 1 )
                                                jQuery.event.remove( this, namespaces[0], liveHandler );
                                }
                        }
@@ -413,11 +369,69 @@ jQuery.event = {
        }
 };
 
-function stopImmediatePropagation(){
-       this._sip = 1;
-       this.stopPropagation();
+jQuery.Event = function( src ){
+       // Allow instantiation without the 'new' keyword
+       if( !this.preventDefault )
+               return new jQuery.Event(src);
+       
+       // Event object
+       if( src && src.type ){
+               this.originalEvent = src;
+               this.type = src.type;
+       // Event type
+       }else
+               this.type = src;
+
+       // timeStamp is buggy for some events on Firefox(#3843)
+       // So we won't rely on the native value
+       this.timeStamp = now();
+       
+       // Mark it as fixed
+       this[expando] = true;
+};
+
+function returnFalse(){
+       return false;
 }
+function returnTrue(){
+       return true;
+}
+
+// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
+// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
+jQuery.Event.prototype = {
+       preventDefault: function() {
+               this.isDefaultPrevented = returnTrue;
+
+               var e = this.originalEvent;
+               if( !e )
+                       return;
+               // if preventDefault exists run it on the original event
+               if (e.preventDefault)
+                       e.preventDefault();
+               // otherwise set the returnValue property of the original event to false (IE)
+               e.returnValue = false;
+       },
+       stopPropagation: function() {
+               this.isPropagationStopped = returnTrue;
 
+               var e = this.originalEvent;
+               if( !e )
+                       return;
+               // if stopPropagation exists run it on the original event
+               if (e.stopPropagation)
+                       e.stopPropagation();
+               // otherwise set the cancelBubble property of the original event to true (IE)
+               e.cancelBubble = true;
+       },
+       stopImmediatePropagation:function(){
+               this.isImmediatePropagationStopped = returnTrue;
+               this.stopPropagation();
+       },
+       isDefaultPrevented: returnFalse,
+       isPropagationStopped: returnFalse,
+       isImmediatePropagationStopped: returnFalse
+};
 // Checks if an event happened on an element within another element
 // Used in jQuery.event.special.mouseenter and mouseleave handlers
 var withinElement = function(event) {
@@ -473,14 +487,20 @@ jQuery.fn.extend({
                });
        },
 
-       trigger: function( type, data, fn ) {
+       trigger: function( type, data ) {
                return this.each(function(){
-                       jQuery.event.trigger( type, data, this, true, fn );
+                       jQuery.event.trigger( type, data, this );
                });
        },
 
-       triggerHandler: function( type, data, fn ) {
-               return this[0] && jQuery.event.trigger( type, data, this[0], false, fn );
+       triggerHandler: function( type, data ) {
+               if( this[0] ){
+                       var event = jQuery.Event(type);
+                       event.preventDefault();
+                       event.stopPropagation();
+                       jQuery.event.trigger( event, data, this[0] );
+                       return event.result;
+               }               
        },
 
        toggle: function( fn ) {
@@ -519,35 +539,54 @@ jQuery.fn.extend({
                // Otherwise, remember the function for later
                else
                        // Add the function to the wait list
-                       jQuery.readyList.push( function() { return fn.call(this, jQuery); } );
+                       jQuery.readyList.push( fn );
 
                return this;
        },
        
        live: function( type, fn ){
-               jQuery(document).bind( liveConvert(type, this.selector), this.selector, fn );
+               var proxy = jQuery.event.proxy( fn );
+               proxy.guid += this.selector + type;
+
+               jQuery( this.context ).bind( liveConvert(type, this.selector), this.selector, proxy );
+
                return this;
        },
        
        die: function( type, fn ){
-               jQuery(document).unbind( liveConvert(type, this.selector), fn );
+               jQuery( this.context ).unbind( liveConvert(type, this.selector), fn ? { guid: fn.guid + this.selector + type } : null );
                return this;
        }
 });
 
 function liveHandler( event ){
-       var check = RegExp("(^|\\.)" + event.type + "(\\.|$)");
+       var check = new RegExp("(^|\\.)" + event.type + "(\\.|$)"),
+               stop = true,
+               elems = [];
+
        jQuery.each(jQuery.data(this, "events").live || [], function(i, fn){
                if ( check.test(fn.type) ) {
                        var elem = jQuery(event.target).closest(fn.data)[0];
                        if ( elem )
-                               jQuery.event.trigger( event.type, fn.data, elem, false, fn, false );
+                               elems.push({ elem: elem, fn: fn });
                }
        });
+
+       elems.sort(function(a,b) {
+               return jQuery.data(a.elem, "closest") - jQuery.data(b.elem, "closest");
+       });
+       
+       jQuery.each(elems, function(){
+               event.currentTarget = this.elem;
+               if ( this.fn.call(this.elem, event, this.fn.data) === false )
+                       return (stop = false);
+       });
+
+       return stop;
 }
 
 function liveConvert(type, selector){
-       return ["live", type, selector.replace(/\./g, "_")].join(".");
+       return ["live", type, selector.replace(/\./g, "`").replace(/ /g, "|")].join(".");
 }
 
 jQuery.extend({
@@ -564,7 +603,7 @@ jQuery.extend({
                        if ( jQuery.readyList ) {
                                // Execute all of them
                                jQuery.each( jQuery.readyList, function(){
-                                       this.call( document );
+                                       this.call( document, jQuery );
                                });
 
                                // Reset the list of functions
@@ -604,7 +643,7 @@ function bindReady(){
 
                // If IE and not an iframe
                // continually check to see if the document is ready
-               if ( document.documentElement.doScroll && !window.frameElement ) (function(){
+               if ( document.documentElement.doScroll && window == window.top ) (function(){
                        if ( jQuery.isReady ) return;
 
                        try {
@@ -638,6 +677,9 @@ jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
 // Prevent memory leaks in IE
 // And prevent errors on refresh with events like mouseover in other browsers
 // Window isn't included so as not to unbind existing unload events
+// More info:
+//  - http://isaacschlueter.com/2006/10/msie-memory-leaks/
+//  - https://bugzilla.mozilla.org/show_bug.cgi?id=252542
 jQuery( window ).bind( 'unload', function(){ 
        for ( var id in jQuery.cache )
                // Skip the window