Implementation of $ (el) .trigger ('my-event', {some: 'data'}); in native js

I will be grateful for the help in how to implement $ (el) .trigger ('my-event', {some: 'data'}); in native js (without using jquery).
I was able to implement a binder without jquery.

        if (window.addEventListener) {
        window.addEventListener(event, func, false);
        }
        else if (window.attachEvent) {
           window.attachEvent(event, func);
        }

I forgot to mention it needs to be supported in IE8 to be more specific. I need a custom trigger 'my-event', not my own trigger, like 'click'

+4
source share
2 answers

Using an EventEmitter :

var ee = new EventEmitter();

// Add a listener
ee.addListener('myCustomEvent', function(){
  console.log(arguments) // yay!
});

// Emit custom event
ee.emitEvent('myCustomEvent', ['some', 'arguments'])
+1
source

, jQuery Vanilla Javascript : http://youmightnotneedjquery.com/

$(el).trigger('change'); 

 if (document.createEvent) {
      var event = document.createEvent('HTMLEvents');
      event.initEvent('change', true, false);
      el.dispatchEvent(event);
    } else {
      el.fireEvent('onchange');
    }
0

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


All Articles