I’m trying this jQuery way of pub-sub and it works only partially:
<button id="button1">click1</button>
<button id="button2">click2</button>
<div id="div1">div1</div>
$("button:first").bind('bla', function (e, text) {
alert("bla1 " + text);
});
$("#div1").bind('bla', function (e, text) {
alert("div " + e, text);
});
$("button:last").click(function () {
$("button:first").trigger('bla', ["ilya"]);
});
Why is the event only triggered on button1 but not on div1?
UPDATE:
Is there a way to trigger all binded custom events without calling the element they are binded to?
You’d need to trigger it on the div as well:
EDIT
Saw your followup question. It’s not entirely clear to me what the use case is here, but my suggestion would be one of two approaches:
—1— Add a CSS class e.g.
class="my-listener"to any elements you want to listen your custom event on:…and…
…then trigger the event like this:
That should work.
—2— Just trigger the event on the
windowobject, and have a single listener that has logic to do what you need for each element in the single listener:Which approach you use (and I’m sure there are others) just depends on what it is you’re trying to accomplish.
Cheers