在上一篇《jQuery学习-事件之绑定事件(一)》我们了解了jQuery的add方法,今天我们来学习下dispatch方法:
dispatch: function( event ) { //这里是修正event对象的属性,处理兼容性问题 event = jQuery.event.fix( event ); var i, ret, handleObj, matched, j, handlerQueue = [],//事件队列 args = slice.call( arguments ),//获取第一参数为event handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],//从缓存系统中获取改标签的事件对象 special = jQuery.event.special[ event.type ] || {};// 对象用于某些事件类型的特殊行为和属性 // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers );//处理事件队列,过滤,排序等操作 //先运行代理事件,且没有阻止冒泡 i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {//在这里我们取出了在绑定事件的组合的对象 // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data;//在这里我们可以在执行事件的时通过event.data来访问自定的数据 //真正触发执行事件的地方 ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault();//阻止默认行为 event.stopPropagation();//阻止冒泡 } } } } } //特殊事件的处理 if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result;
}
好了,今天就到这里了,一点一点偷!