Is there a way to implement EventTarget with plain JS?

I am trying (possibly in vain) to come up with a way to use the publication-subscription template, a) without using libraries and b) minimizing the template code in the modules that use it. So far, the best I've come up with is:

var handle = document.createElement();
var unsubscribe = AwesomeModule.subscribe(handle);

handle.addEventListener('awesome', function() {
    console.log('awesome');
});

This will work very well, except that people using the AwesomeModule may be confused by having to provide a random DOM element that is not used as an element.

I tried the following and it does not work too well:

var handle = Object.create(EventTarget);
var unsubscribe = AwesomeModule.subscribe(handle);

handle.addEventListener('awesome', function(){
    console.log('awesome')
});

I get it TypeError: Object [object Object] has no method 'addEventListener'. Interestingly, it does not seem to look in the prototype chain, although the descriptor has an EventTarget as its prototype.

? EventTarget JS? , AwesomeModule?

: , , , EventTarget, , , . , Chrome Object.create(EventTarget) , , , addEventListener . , . - ? - , W3 EventTarget ""?

+4
3

, - "". JavaScript , Java, , , , . , addEventListener EventTarget ( , ). , , - vanilla EventTarget, , , window.addEventListener .

+2

, . polyfill IE9 10, .

, , , .

var on = addEventListener.bind(window),
 off = removeEventListener.bind(window),
 emit = function(name, val) {
    dispatchEvent(new CustomEvent(name, {
        detail: val
    }));
};



// demo:
on("test", function(e){ alert(e.detail);});
emit("test", "Number is " + Math.random());

, (~ 180 ), .

+1

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


All Articles