简体   繁体   中英

Multiple Components listening via eventlistener

I was wondering why you're not allowed to have multiple similar eventListeners on a single node? I imagine the case where I have multiple partials of the same type that use a single node to communicate with eachother through CustomEvents. But that doesnt seem to be working because they do all share the same EventListener and thus only one of them is able to listen and process the event.

Why is that?

Thanks!

EDIT: little code snippet:

I have

node.addEventListener("customEvent", this.func, false);

and

node.addEventListener("customEvent", this.func, false);

in two different places and this.func points to the same function but in different contextes and would eventually trigger different things. But the second listener never gets called because for some reason this something seems to assumes that their the same probably because the signature is alike or whatever.

EDIT2: I'm basically referring to this. https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener#Multiple_identical_event_listeners

In Java you can add multiple listeners. But, honestly, I dont like this approach. In most of the cases, you only need to trigger 1 interface/object (you are adding a overhead, logic for multiple interfaces where only one is used).

I like more the Android approach: setOn....Event (looks like JS is this way) instead of addActionListener(...) of Java.

When you need multiple triggers, you could override like:

 obj.setOnEvent(function() {
    doTheOtherEventTrigger();
    doOneMoreEventTrigger();
    ...
 }

You can attach multiple similar event handlers to a node by using addEventListener.

node.addEventListener("click", function(){alert(1)}, false);
node.addEventListener("click", function(){alert(2)}, false);

Should give an alert twice. When you assign anonymous function this works.

However you can assign multiple listeners referring to the same function and event by using bind.

var a = this.func.bind();
document.getElementById("start").addEventListener("click", a, false);   
var b = this.func.bind();
document.getElementById("start").addEventListener("click", b, false);   

This will alert twice. Since the function wrapper is different, it's being treated as an unique event.

You can't assign an event handler twice through node.onclick, because it's a property. When you assign it twice it will just overwrite the first handler. Event listeners were invented to cope with this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM