jquery event: closes #3772. The extra function on $.event.trigger isn't supported...
[jquery.git] / src / event.js
index 92252a2..414f942 100644 (file)
@@ -13,7 +13,7 @@ jQuery.event = {
 
                // For whatever reason, IE has trouble passing the window object
                // around, causing it to be cloned in the process
-               if ( jQuery.browser.msie && elem.setInterval )
+               if ( elem.setInterval && elem != window )
                        elem = window;
 
                // Make sure that the function being executed has a unique ID
@@ -53,12 +53,15 @@ jQuery.event = {
                // jQuery(...).bind("mouseover mouseout", fn);
                jQuery.each(types.split(/\s+/), function(index, type) {
                        // Namespaced event handlers
-                       var parts = type.split(".");
-                       type = parts.shift();
-                       handler.type = parts.sort().join(".");
+                       var namespaces = type.split(".");
+                       type = namespaces.shift();
+                       handler.type = namespaces.slice().sort().join(".");
 
                        // Get the current list of functions bound to this event
                        var handlers = events[type];
+                       
+                       if ( jQuery.event.specialAll[type] )
+                               jQuery.event.specialAll[type].setup.call(elem, data, namespaces);
 
                        // Init the event handler queue
                        if (!handlers) {
@@ -67,7 +70,7 @@ jQuery.event = {
                                // Check for a special event handler
                                // Only use addEventListener/attachEvent if the special
                                // events handler returns false
-                               if ( !jQuery.event.special[type] || jQuery.event.special[type].setup.call(elem,data) === false ) {
+                               if ( !jQuery.event.special[type] || jQuery.event.special[type].setup.call(elem, data, namespaces) === false ) {
                                        // Bind the global event handler to the element
                                        if (elem.addEventListener)
                                                elem.addEventListener(type, handle, false);
@@ -114,9 +117,9 @@ jQuery.event = {
                                // jQuery(...).unbind("mouseover mouseout", fn);
                                jQuery.each(types.split(/\s+/), function(index, type){
                                        // Namespaced event handlers
-                                       var namespace = type.split(".");
-                                       type = namespace.shift();
-                                       namespace = RegExp(namespace.sort().join(".*\\.") + "(\\.|$)");
+                                       var namespaces = type.split(".");
+                                       type = namespaces.shift();
+                                       var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");
 
                                        if ( events[type] ) {
                                                // remove the given handler for the given type
@@ -129,11 +132,14 @@ jQuery.event = {
                                                                // Handle the removal of namespaced events
                                                                if ( namespace.test(events[type][handler].type) )
                                                                        delete events[type][handler];
+                                                                       
+                                               if ( jQuery.event.specialAll[type] )
+                                                       jQuery.event.specialAll[type].teardown.call(elem, namespaces);
 
                                                // remove generic event handler if no more handlers exist
                                                for ( ret in events[type] ) break;
                                                if ( !ret ) {
-                                                       if ( !jQuery.event.special[type] || jQuery.event.special[type].teardown.call(elem) === false ) {
+                                                       if ( !jQuery.event.special[type] || jQuery.event.special[type].teardown.call(elem, namespaces) === false ) {
                                                                if (elem.removeEventListener)
                                                                        elem.removeEventListener(type, jQuery.data(elem, "handle"), false);
                                                                else if (elem.detachEvent)
@@ -157,76 +163,72 @@ jQuery.event = {
                }
        },
 
-       trigger: function(type, data, elem, donative, extra) {
-               // Clone the incoming data, if any
-               data = jQuery.makeArray(data);
+       trigger: function( event, data, elem) {
+               // Event object or event type
+               var type = event.type || event;
+
+               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 ) {
-                       type = type.slice(0, -1);
-                       var exclusive = true;
+                       event.type = type = type.slice(0, -1);
+                       event.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( type, data, this.handle.elem );
+                                               jQuery.event.trigger( event, data, this.handle.elem );
                                });
 
                // Handle triggering a single element
                } else {
+
                        // don't do events on text and comment nodes
                        if ( elem.nodeType == 3 || elem.nodeType == 8 )
                                return undefined;
 
-                       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
+                       // Clone the incoming data, if any
+                       data = jQuery.makeArray(data);
+
+                       // AT_TARGET phase (not bubbling)
+                       if( !event.target ){
+                               // Clean up in case it is reused
+                               event.result = undefined;
+                               event.target = elem;
                        }
 
-                       // Enforce the right trigger type
-                       data[0].type = type;
-                       if ( exclusive )
-                               data[0].exclusive = true;
+                       // Fix for custom events
+                       event.currentTarget = elem;
+
+                       data.unshift( event );
+
+                       var fn = jQuery.isFunction( elem[ type ] );
 
                        // Trigger the event, it is assumed that "handle" is a function
                        var handle = jQuery.data(elem, "handle");
                        if ( handle )
-                               val = handle.apply( elem, data );
+                               handle.apply( elem, data );
 
                        // 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;
+                               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;
-                       }
+                       data.shift();
 
                        // Trigger the native events (except for clicks on links)
-                       if ( fn && donative !== false && val !== false && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
+                       if ( event.target === elem && fn && !event.isDefaultPrevented() && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
                                this.triggered = true;
                                try {
                                        elem[ type ]();
@@ -234,24 +236,33 @@ jQuery.event = {
                                } catch (e) {}
                        }
 
+                       if ( !event.isPropagationStopped() ) {
+                               var parent = elem.parentNode || elem.ownerDocument;
+                               if ( parent )
+                                       jQuery.event.trigger(event, data, parent);
+                       }
+
+                       // Clean up, in case the event object is reused
+                       event.target = null;
+
                        this.triggered = false;
                }
-
-               return val;
        },
 
        handle: function(event) {
                // returned undefined or false
-               var val, ret, namespace, all, handlers;
+               var all, handlers;
 
                event = arguments[0] = jQuery.event.fix( event || window.event );
 
                // Namespaced event handlers
-               namespace = event.type.split(".");
-               event.type = namespace.shift();
-               namespace = RegExp(namespace.sort().join(".*\\.") + "(\\.|$)");
+               var namespaces = event.type.split(".");
+               event.type = namespaces.shift();
+
                // Cache this now, all = true means, any handler
-               all = !namespace && !event.exclusive;
+               all = !namespaces.length && !event.exclusive;
+               
+               var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");
 
                handlers = ( jQuery.data(this, "events") || {} )[event.type];
 
@@ -265,26 +276,24 @@ jQuery.event = {
                                event.handler = handler;
                                event.data = handler.data;
 
-                               ret = handler.apply( this, arguments );
+                               var ret = handler.apply(this, arguments);
 
-                               if ( val !== false )
-                                       val = ret;
-
-                               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] )
@@ -293,38 +302,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
@@ -373,47 +357,124 @@ jQuery.event = {
                        setup: bindReady,
                        teardown: function() {}
                }
+       },
+       
+       specialAll: {
+               live: {
+                       setup: function( selector, namespaces ){
+                               jQuery.event.add( this, namespaces[0], liveHandler );
+                       },
+                       teardown:  function( namespaces ){
+                               if ( namespaces.length ) {
+                                       var remove = 0, name = RegExp("(^|\\.)" + namespaces[0] + "(\\.|$)");
+                                       
+                                       jQuery.each( (jQuery.data(this, "events").live || {}), function(){
+                                               if ( name.test(this.type) )
+                                                       remove++;
+                                       });
+                                       
+                                       if ( remove <= 1 )
+                                               jQuery.event.remove( this, namespaces[0], liveHandler );
+                               }
+                       }
+               }
        }
 };
 
-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;
+               this.timeStamp = src.timeStamp;
+       // Event type
+       }else
+               this.type = src;
+
+       if( !this.timeStamp )
+               this.timeStamp = now();
+       
+       // Mark it as fixed
+       this[expando] = true;
+};
+
+function returnFalse(){
+       return false;
+}
+function returnTrue(){
+       return true;
 }
 
-if ( !jQuery.browser.msie ){   
-       // Checks if an event happened on an element within another element
-       // Used in jQuery.event.special.mouseenter and mouseleave handlers
-       var withinElement = function(event) {
-               // Check if mouse(over|out) are still within the same parent element
-               var parent = event.relatedTarget;
-               // Traverse up the tree
-               while ( parent && parent != this )
-                       try { parent = parent.parentNode; }
-                       catch(e) { parent = this; }
-               
-               if( parent != this ){
-                       // set the correct event type
-                       event.type = event.data;
-                       // handle event if we actually just moused on to a non sub-element
-                       jQuery.event.handle.apply( this, arguments );
-               }
-       };
+// 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) {
+       // Check if mouse(over|out) are still within the same parent element
+       var parent = event.relatedTarget;
+       // Traverse up the tree
+       while ( parent && parent != this )
+               try { parent = parent.parentNode; }
+               catch(e) { parent = this; }
        
-       jQuery.each({ 
-               mouseover: 'mouseenter', 
-               mouseout: 'mouseleave'
-       }, function( orig, fix ){
-               jQuery.event.special[ fix ] = {
-                       setup: function(){
-                               jQuery.event.add( this, orig, withinElement, fix );
-                       },
-                       teardown: function(){
-                               jQuery.event.remove( this, orig, withinElement );
-                       }
-               };                         
-       });
-}
+       if( parent != this ){
+               // set the correct event type
+               event.type = event.data;
+               // handle event if we actually just moused on to a non sub-element
+               jQuery.event.handle.apply( this, arguments );
+       }
+};
+       
+jQuery.each({ 
+       mouseover: 'mouseenter', 
+       mouseout: 'mouseleave'
+}, function( orig, fix ){
+       jQuery.event.special[ fix ] = {
+               setup: function(){
+                       jQuery.event.add( this, orig, withinElement, fix );
+               },
+               teardown: function(){
+                       jQuery.event.remove( this, orig, withinElement );
+               }
+       };                         
+});
 
 jQuery.fn.extend({
        bind: function( type, data, fn ) {
@@ -438,14 +499,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 ) {
@@ -484,12 +551,40 @@ 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 );
+               return this;
+       },
+       
+       die: function( type, fn ){
+               jQuery(document).unbind( liveConvert(type, this.selector), fn );
+               return this;
        }
 });
 
+function liveHandler( event ){
+       var check = RegExp("(^|\\.)" + event.type + "(\\.|$)"),
+               stop = true;
+
+       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 && fn.call(elem, event, fn.data) === false )
+                               stop = false;
+               }
+       });
+       return stop;
+}
+
+function liveConvert(type, selector){
+       return ["live", type, selector.replace(/\./g, "_")].join(".");
+}
+
 jQuery.extend({
        isReady: false,
        readyList: [],
@@ -504,7 +599,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