最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can the children listencapture to the parent's event - Stack Overflow

programmeradmin5浏览0评论

How can the parent fire the custom event to notify its children/siblings? For example:

<div id="div1">
   <div id="div2"></div>
</div>

div2 had addEventListener('customEvent2', doSth), and then div1 will fire a custom event (customEvnet2), but this will never trigger div2's doSth function.

Sample code: /

The "div 1 trigger customEvent 2" button never works

so when a parent fire a custom event (dispatchEvent[IE9]/fireEvent[IE9-]/trigger[jQuery]), the children can not capture the event.

Is there any workaround?

How can the parent fire the custom event to notify its children/siblings? For example:

<div id="div1">
   <div id="div2"></div>
</div>

div2 had addEventListener('customEvent2', doSth), and then div1 will fire a custom event (customEvnet2), but this will never trigger div2's doSth function.

Sample code: http://jsfiddle/r4tcT/2/

The "div 1 trigger customEvent 2" button never works

so when a parent fire a custom event (dispatchEvent[IE9]/fireEvent[IE9-]/trigger[jQuery]), the children can not capture the event.

Is there any workaround?

Share Improve this question edited Jul 13, 2022 at 19:27 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Sep 19, 2012 at 22:43 CLBCLB 1331 silver badge4 bronze badges 1
  • 3 I believe that this is not possible, unless you make some kind of hack, because events going up on the DOM tree like bubbles and never going down to children – haynar Commented Sep 19, 2012 at 22:49
Add a ment  | 

4 Answers 4

Reset to default 7

The difference you are talking about is either between the 'Capturing' event model or the 'Bubbling' event model. jQuery's trigger operates on the Bubble model probably because this is the more supported event model -- mainly thanks to Internet Explorer. The Bubble model only travels backwards up through an elements parents... this is the reason why your events don't trigger on div2 when fired from div1, as it is always bubbling up and not down.

I've not tried custom events before with native functions but most modern browsers allow for you to decide which type of model you use when you set the event listener:

addEventListener (type, listener[, useCapture])

https://developer.mozilla/en-US/docs/DOM/element.addEventListener

Basically if you use true as the final argument the event listener should trigger in the Capture phase (which is when the event is travelling down the dom tree). If set to false the event will trigger in the bubbling phase which occurs when travelling back up the dom tree.

This has been discussed here:

Event Capturing vs Event Bubbling

As I've said whether this will work for bespoke events I'm not sure. I am pretty certain you can not do this with jQuery (as of yet) probably due to the lack of support in older browsers.

Correction

It appears what I guessed at above doesn't work. I thought as much due to the term 'Capturing' kind of makes you think about capturing user input -- and when bespoke events are involved there is no way to define a new kind of user input. So with that in mind I put together this quick jQuery plugin... it's only been roughly tested, but the logic should be sound - hope it's useful:

/**
 * unbubble v0.2
 *
 * trigger an event down through the children of a collection, 
 * rather than up through it's parents
 *
 *  @update 2013/03/18 - fixed the problem of triggering bubble phase each
 *    step down the element tree as pointed out by @vine.
 */
$.fn.unbubble = function( eventNames ){
  var names = eventNames.split(' '), 
      non = names.length, 
      args = Array.prototype.slice.call(arguments);
  /// our own trigger function designed to bubble down... not up!
  var trigger = function(){
    var i, events, elm = $(this);
    /// make sure we can read the events array
    if ( $._data ) {
      /// make sure events is defined
      if ( (events = $._data(this, 'events')) ) {
        /// do a quick check, saves firing trigger on every element found
        for ( i=0; i<non; i++ ) {
          /// make sure our eventName appears in the event list
          if ( names[i] && ( names[i] in events ) ) {
            /// trigger the standard jQuery trigger function
            elm.triggerHandler.apply(elm, args);
            /// escape as trigger should fire for multiple names
            break;
          }
        }
      }
    }
    /// if we can't access the events array, just trigger and hope
    else {
      /// trigger the standard jQuery trigger function
      elm.triggerHandler.apply(elm, args);
    }
    /// trigger for all the children, and on, and on...
    elm.children().each(trigger);
  };
  /// foreach element trigger now...
  this.each(trigger);
}

/**
 * Example usage
 */
$(function(){
  /// bind our event as usual
  $('.div2').bind('customEvent', function(){
    alert('I should trigger!');
  });
  /// rather than use trigger, fire with unbubble
  $('#div1').unbubble( 'customEvent' );
});

The answer of pebbl is good but it has flaw. The capturing phase is somehow simulated by the normal triggering of events from document down to the concerned element. But the issue will be, calling the standard jQuery trigger function on any element will immediately followed by a bubbling phase starting from that element and up. So i believe he can stick with accessing the events data directly from the collection of elements and calling it directly not using the standard trigger function , something like this

var JQ_LT_17 = parseFloat($.fn.jquery) < 1.7;

function getEventsData(element) {
        return JQ_LT_17 ? $(element).data('events') : $._data(element).events;
}

Code snippet borrowed form jQuery.bind-first library v0.1 Vladimir Zhuravlev

customEvent2 is only bound to div2. When you try to trigger it on div1, nothing happens because that event doesn't exist for div1.

If you want to fire customEvent2, it has to be triggered on an element (or child of one) it is actually bound to.

I have played a little bit with the code and here is what I now have. It is a hack, but maybe it could help you to solve your problem?

发布评论

评论列表(0)

  1. 暂无评论