孩子怎么能听/捕捉父母的事件 [英] how can the children listen/capture to the parent's event

查看:93
本文介绍了孩子怎么能听/捕捉父母的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

父母如何触发自定义事件来通知其子女/兄弟姐妹?
例如:

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

div2有addEventListener('customEvent2',doSth),然后div1将触发自定义事件(customEvnet2 )。但这不会触发div2的doSth函数



示例代码: http://jsfiddle.net/r4tcT/2/



div 1 trigger customEvent 2按钮从不工作

$ b所以当一个父级触发自定义事件(dispatchEvent [IE9] / fireEvent [IE9 - ] / trigger [jQuery])时,孩子们无法捕获事件。



是否有任何解决方法?

解决方案

您正在谈论的区别在于捕获'事件模型或'冒泡'事件模型。 jQuery的触发器在Bubble模型上运行,可能是因为这是更受支持的事件模型 - 主要是因为Internet Explorer。泡泡模型只能通过元素父母向后移动...这就是为什么您的事件在 div2 中从 div1触发时不会触发,因为它总是冒泡而不是下来。



我没有尝试使用本机功能之前的自定义事件,但大多数现代浏览器允许您确定设置事件侦听器时使用的模型类型:

  addEventListener(type,listener [,useCapture]) 

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



基本上,如果您使用 true 作为最终参数,则事件侦听器应在Capture阶段(当事件沿着dom树向下行进时)触发时, 。如果设置为false,则事件将在冒泡阶段触发,当发生在返回dom树时发生。



这里已经讨论过:



事件捕获与事件冒泡



正如我所说,这是否适用于定制活动,我不知道。我确定你不能这样做,因为jQuery (至今)可能是由于旧版浏览器缺乏支持。



更正



看起来我以前猜到的不行。我认为,由于捕获这个术语,您可以考虑捕获用户输入 - 当涉及到定制事件时,无法定义新的用户输入。所以考虑到这一点,我把这个快速的jQuery插件放在一起...它只是被粗略测试,但逻辑应该是声音 - 希望它是有用的:

  / ** 
* unbubble v0.2
*
*触发一个事件,通过一个集合的孩子,
*而不是通过它的父母
*
* @update 2013/03/18 - 修正了引发泡沫阶段的问题,每个
*按照@vine指出的步骤放下元素树。
* /
$ .fn.unbubble = function(eventNames){
var names = eventNames.split(''),
non = names.length,
args = Array.prototype.slice.call(arguments);
///我们自己的触发器功能设计为泡沫不起来!
var trigger = function(){
var i,events,elm = $(this);
///确保我们可以读取事件数组
if($ ._ data){
///确保事件定义为
if((events = $ ._ data (这个'事件'))){
///快速检查,为每个找到的元素保存触发触发器
(i = 0; i<非; i ++){
///确保我们的eventName出现在事件列表
if(names [i]&(names [i] in events)){
///触发标准的jQuery触发器函数
elm.triggerHandler.apply(elm,args);
/// escape as trigger should fire for multiple names
break;
}
}
}
}
///如果我们无法访问事件数组,只需触发并希望
else {
///触发标准的jQuery触发器函数
elm.triggerHandler.apply(elm,args);
}
///触发所有的孩子,以及on和on ...
elm.children()。each(trigger);
};
/// foreach元素触发器现在...
this.each(trigger);
}

/ **
*使用示例
* /
$(function(){
///将我们的事件绑定为通常
$('。div2')。bind('customEvent',function(){
alert('I should trigger!');
});
// /而不是使用触发器,用unbubble消息
$('#div1')。unbubble('customEvent');
});


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.net/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?

解决方案

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.org/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' );
});

这篇关于孩子怎么能听/捕捉父母的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆