How do I create my own event in javascript?


I am interested in whether it is possible to create my own event on javaScript so that an event listener can be placed on it.

For example, there are two blocks, how to create an event if someone clicked on the first block, this is the event click_1, and if on the second block, the event click_2.

You need to be able to hang a handler on these events, as on a normal click:

$( "#target" ).click_1(function() {
  alert( "click_1" );
});

Example of markup:

.block_1{
  width:300px;
  height:300px;
  background-color: aqua;
}

.block_2{
  width:300px;
  height:300px;
  background-color: chartreuse;
}
<div class="block_1"> 1 </div>
<div class="block_2"> 2 </div>

How to implement this on js?

Author: HELO WORD, 2016-08-05

2 answers

Thanks to the methods trigger and triggerHandler (triggerHandler you can call it a stripped-down version trigger) you can generate standard and custom events http://api.jquery.com/trigger/ http://api.jquery.com/triggerHandler/

You can also group common events (events of a single component, for example) using namespace https://api.jquery.com/event.namespace/

$element.on('event.namespace', function (e) {
  ...
});
...
$element.trigger('event.namespace');

However, in your example, it's actually better to subscribe to events of a specific element:

$('.block_1').on('click', function () {
  alert('Block 1');
});
$('.block_2').on('click', function () {
  alert('Block 2');
});
.block_1 {
  width:300px;
  height:300px;
  background-color: aqua;
}

.block_2 {
  width:300px;
  height:300px;
  background-color: chartreuse;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="block_1">1</div>
<div class="block_2">2</div>

You can even use a single handler:

$('.js-block').on('click', function () {
  alert('Block ' + $(this).data('blockNum'));
});
.block_1 {
  width:300px;
  height:300px;
  background-color: aqua;
}

.block_2 {
  width:300px;
  height:300px;
  background-color: chartreuse;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="block_1 js-block" data-block-num="1">1</div>
<div class="block_2 js-block" data-block-num="2">2</div>

And delegation will allow you to catch events of dynamically created elements:

var $body = $('body'),
    addBlock = (function  () {
  var $lastBlock = $('.js-block').last(),
      className = ['block_2', 'block_1'],
      counter = 0 || $lastBlock.data('blockNum');
  
  return function () {
    var $block = $('<div/>');
    counter++;
    $block.data('blockNum', counter);
    $block.addClass(className[counter % 2]).addClass('js-block').text(counter);
    $body.append($block);
  };
})();

$body.on('click', '.js-block', function () {
  alert('Block ' + $(this).data('blockNum'));
  addBlock();
});
.block_1 {
  width:300px;
  height:300px;
  background-color: aqua;
}

.block_2 {
  width:300px;
  height:300px;
  background-color: chartreuse;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="block_1 js-block" data-block-num="1">1</div>
<div class="block_2 js-block" data-block-num="2">2</div>

But if you still need to catch globally generated events (just do not do this in the conditions of this example - it will not be a very good tone), use the pattern "Mediator". Its simple implementation for jquery can be found here https://github.com/cowboy/jquery-tiny-pubsub

/*! Tiny Pub/Sub - v0.7.0 - 2013-01-29
* https://github.com/cowboy/jquery-tiny-pubsub
* Copyright (c) 2013 "Cowboy" Ben Alman; Licensed MIT */
(function($) {

  var o = $({});

  $.subscribe = function() {
    o.on.apply(o, arguments);
  };

  $.unsubscribe = function() {
    o.off.apply(o, arguments);
  };

  $.publish = function() {
    o.trigger.apply(o, arguments);
  };

}(jQuery));

$('.js-block').on('click', function() {
  $.publish('click_' + $(this).data('blockNum'));
});

$.subscribe('click_1', function() {
  alert('Block 1');
});

$.subscribe('click_2', function() {
  alert('Block 2');
});
.block_1 {
  width: 300px;
  height: 300px;
  background-color: aqua;
}
.block_2 {
  width: 300px;
  height: 300px;
  background-color: chartreuse;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="block_1 js-block" data-block-num="1">1</div>
<div class="block_2 js-block" data-block-num="2">2</div>

I advise you to read more about design patterns http://largescalejs.ru/

 7
Author: qodunpob, 2016-08-05 07:02:20

In pure JS, see Creating and calling events:

var click1 = new Event('click_1')
  ,click2 = new Event('click_2')
  ,b1 = document.getElementById('block_1')
  ,b2 = document.getElementById('block_2')
;

// слушать события
b1.addEventListener('click_1', function (e) { console.log("Clicked 1"); }, false);
b2.addEventListener('click_2', function (e) { console.log("Clicked 2"); }, false);

// вызвать события
b2.dispatchEvent(click2);
#block_1,#block_2{width: 50px;height: 50px;margin: 10px;text-align: center;float: left;cursor: pointer;}#block_1{background-color: aqua}#block_2{background-color: chartreuse}
<div id="block_1">1</div>
<div id="block_2">2</div>

At the same time, the standard click event remains, and if you want to call the created events by click, you need to catch the click, and from its handler do dispatchEvent(ваше нестандартное событие)

 3
Author: Sergiks, 2016-08-05 06:52:33