<...">

JQuery namespace doesn't cause bubble what custom event

HTML:

<div class="parent">
    <div class="child1" >
    </div>
    <div class="child2">
    </div>
</div>

<a class="btn1">customClick.btn1</a>
<a class="btn2">customClick.btn2</a>

JavaScript:

 jQuery('div.child1')
    .bind('customClick.btn1', function () {
        alert('child1 reacted to customClick.btn1');
    });


 jQuery('div.child2')
    .bind('customClick.btn2', function () {
        alert('child2 reacted to customClick.btn2');
    });

 jQuery('div.parent')
    .bind('customClick.btn1', function (e) {
      alert('parent reacted to customClick.btn1');
    })
    .bind('customClick.btn2', function (e) {
       alert('parent reacted to customClick.btn2');
    });

jQuery('a.btn1')
    .click(function(){
        jQuery('div.child1').trigger('customClick.btn1');
    });

jQuery('a.btn2')
    .click(function(){
        jQuery('div.child2').trigger('customClick.btn2');
    });

When I click a.btn1, as expected, the event is customClick.btn1processed div.child1, not div.child2. The event is not expected to customClicktrigger bubbles and fire handlers on div.parentfor customClick.btn1and customClick.btn2. It is right? Is there a way to create custom events with their namespace? In other words, when it is triggered customClick.btn1, not all the parent handlers for customClickare processed, but only those that process it customClick.btn1.

+3
source share
2 answers

, , , . . , .

, .parent 2 customClick , . .

: http://api.jquery.com/bind/

eventType (.), . . , .bind('click.name', handler), - , - . Namespacing , .

, , , , , -, .

e.target.className, , . , .


EDIT:

, :

if(e.handleObj.namespace === 'btn1')

EDIT:

@Nick Craver, , . ( ) .

, , Event .

+3

HTML

<div class="parent">
    <div class="child1" >
    </div>
    <div class="child2">
    </div>
</div>

<a class="btn1">customClick.btn1</a>
<a class="btn2">customClick.btn2</a>

JQuery

 jQuery('div.child1')
    .bind('customClick', function (e) {
        if(e.namespace == 'btn1'){
          console.log('child1 reacted to customClick.btn1');
        }
    });


 jQuery('div.child2')
    .bind('customClick', function (e) {
       if(e.namespace == 'btn2'){
          console.log('child2 reacted to customClick.btn2');
       }
    });

 jQuery('div.parent')
    .bind('customClick', function (e) {
      if(e.namespace == 'btn1'){
          console.log('parent reacted to customClick.btn1');
      }
      if(e.namespace == 'btn2'){
          console.log('parent reacted to customClick.btn2');
      }
    })


jQuery('a.btn1')
    .click(function(){
        jQuery('div.child1').trigger({type:'customClick',namespace:'btn1'});
    });

jQuery('a.btn2')
    .click(function(){
        jQuery('div.child2').trigger({type:'customClick',namespace:'btn2'});
    });

, , . jQuery. № 6913 .

+1

Source: https://habr.com/ru/post/1759979/


All Articles