开发者

How do jQuery Custom events work exactly

开发者 https://www.devze.com 2023-02-04 03:54 出处:网络
I can\'t find any good resources on开发者_Go百科 how custom events in jquery are actually implemented.Like how they simulate the event bubbling, etc.This way:

I can't find any good resources on开发者_Go百科 how custom events in jquery are actually implemented. Like how they simulate the event bubbling, etc.


This way:

// bubbling is internal
trigger: function( event, data, elem /*, bubbling */ ) {
// Event object or event type
var type = event.type || event,
    bubbling = arguments[3];

// 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 ( jQuery.event.global[ type ] ) {
        jQuery.each( jQuery.cache, function() {
            if ( this.events && this.events[type] ) {
                jQuery.event.trigger( event, data, this.handle.elem );
            }
        });
    }
}

// ... snip ...
// Trigger the event, it is assumed that "handle" is a function
var handle = elem.nodeType ?
    jQuery.data( elem, "handle" ) :
    (jQuery.data( elem, "__events__" ) || {}).handle;

if ( handle ) {
    handle.apply( elem, data );
}

var parent = elem.parentNode || elem.ownerDocument;
// ... snip ....
if ( !event.isPropagationStopped() && parent ) {
    jQuery.event.trigger( event, data, parent, true );

   } else if ( !event.isDefaultPrevented() ) {
   // ... snip ...
                jQuery.event.triggered = true;
                target[ targetType ]();
    }
}

What's going on here is as follows:

When trigger is called jQuery checks to see if the event is being triggered globally ($.trigger("event_name");).

If it is not being triggered globally, and propagation has not been stopped and the element in question has a parent element (!event.isPropagationStopped() && parent) then jQuery calls the trigger event manually on the parent element.

jQuery.event.trigger( event, data, parent, true );

There is quite a bit more going on -- see event.js in the jQuery source code.


Check out the tutorials

$(document).bind("eventType", ...);
// This is equivalent to the plugin's $.subscribe("eventType", ...);
$(document).trigger("eventType");
// equivalent to plugin's $.publish("eventType");

Also checkout this SO question

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号