Custom事件如何正常工作

Custom事件如何正常工作

本文介绍了jQuery Custom事件如何正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到任何关于如何实际实现jquery中的自定义事件的好资源。就像他们如何模拟事件冒泡等一样。

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

推荐答案

这样:

// 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 ]();
    }
}

这里发生的事情如下:

当调用触发器时,jQuery会检查是否全局触发事件( $。触发器( EVENT_NAME); )。

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

如果全局触发,传播尚未停止有问题的元素有一个父元素(!event.isPropagationStopped()&& parent )然后jQuery在父元素上手动调用触发事件。

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.

这篇关于jQuery Custom事件如何正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 15:05