Skip to content Skip to sidebar Skip to footer

DispatchEvent To All Listeners

Perhaps this is a misconception of mine, but I thought that when you create a custom event, and later create 'elements with event listeners' (listening for that event), that the ev

Solution 1:

A custom event is dispatched to the listeners of a specific target object. It is not dispatched to all listeners of that event no matter which object the event is dispatched to or which object is being listened to? It basically works exactly like a 'click' event works. The event is dispatched only to a specific object and only the listeners for that event attached to that specific object.

If you want a global event and global listeners like you seem to want, then you can create a single known object, have everyone listen to events on that object and then dispatch the event to that object. Then, everyone will get notified of the event.

You may find it easier to just use an eventEmitter object like this.

But, if all you want to do is to change some attribute of a bunch of div objects, then I'd suggest you just put a common class name on them and use document.querySelectorAll() to retrieve all the target elements and then run some code on them. I don't see any particular reason here for custom event listeners as they don't really do what you're doing.

You could use something like this:

function iterateTargets(selector, fn, data) {
    var items = document.querySelectorAll(selector);
    for (var i = 0; i < items.length; i++) {
        fn(items[i], data);
    }
}

iterateTargets(".specials", function(item){
    item.style.backgroundColor = "red;
});

Or a version that works on a style setting without a callback function:

function iterateTargets(selector, fn, data) {
    var items = document.querySelectorAll(selector);
    for (var i = 0; i < items.length; i++) {
        fn(items[i], data);
    }
}

function setStyles(selector, styleName, value) {
    iterateTargets(selector, function(item) {
        item.style[styleName] = value;
    });
}

setStyles(".specials", "backgroundColor", "red");

Post a Comment for "DispatchEvent To All Listeners"