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:
$("button:last").click(function () {
$("button:first, #div1").trigger('bla', ["ilya"]);
});
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:
<button id="button1" class="my-listener">click1</button>;
<button id="button2">click2</button>;
<div id="div1" class="my-listener">div1</div>;
...and...
// Your original lister code is fine. Only need to do these individually (as opposed to my original suggestion, above) if you need each element to do something different when it catches the event)
$("button:first").bind('bla', function (e, text) {
alert("bla1 " + text);
});
$("#div1").bind('bla', function (e, text) {
alert("div " + e, text);
});
...then trigger the event like this:
$('.my-listener').trigger('bla', ["ilya"]);
That should work.
---2--- Just trigger the event on the window object, and have a single listener that has logic to do what you need for each element in the single listener:
$(window).bind('blah', function(event, data){
// Do something for button:last
// Do something with #div1
// etc.
});
$(window).trigger('bla', ['ilya']);
Which approach you use (and I'm sure there are others) just depends on what it is you're trying to accomplish.
Cheers
Because you're not triggering it on the #div1.
$("button:last").click(function () {
$("button:first").trigger('bla', ["ilya"]);
$("#div1").trigger('bla', ["ilya"]); // you need to trigger it
});
http://jsfiddle.net/5XZbY/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With