Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery custom event works only partially

Tags:

jquery

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?

like image 626
ilyo Avatar asked Nov 20 '25 18:11

ilyo


2 Answers

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

like image 152
Madbreaks Avatar answered Nov 23 '25 11:11

Madbreaks


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/

like image 31
cliffs of insanity Avatar answered Nov 23 '25 10:11

cliffs of insanity