Skodsgn
Skodsgn

Reputation: 981

Javascript custom events - trigger to all listeners

I want to create customEvent. For example i have some elements,and every one is listening to this event. When i click on one of them i want to trigger my customEvent. How to make this?

Example:

var customEvent = new Event('customEvent');

var $ul = $('ul');

var $markers = $('#map').find('.markers');

// UL>LI
$ul.delegate('click', 'li', function(){
    customEvent.trigger();
});

$ul.delegate('customEvent', 'li', function(){
    $ul.find('li').removeClass("active");

});

// MAP MARKERS
$markers.on('click', 'li', function(){
    customEvent.trigger();
});

$markers.on('customEvent', function(){
    // do sth
});

Upvotes: 0

Views: 67

Answers (1)

Satpal
Satpal

Reputation: 133403

Its simple, you need to use .trigger() function

Execute all handlers and behaviors attached to the matched elements for the given event type.

Script

ele.on('click', function() {  
      $(this).trigger('customEvent');
      //Or, $(this).trigger(customEvent); 
});

Upvotes: 3

Related Questions