views:

25

answers:

2

In one section of code I have this:

$("#searchbar").trigger("onOptionsApplied");

In another section of code, I have this:

$("#searchbar").bind("onOptionsApplied", function () {
    alert("fdafds");
});

The bind() is executed before the trigger(), but when I view the page, I never get an alert().

Why not? What am I doing wrong with events?

A: 

I also tried it and works fine.

put the bind function in the ready handler and then trigger the event ...it should go smooth

abbas
this should be a comment ;)
Reigel
+1  A: 

Perhaps your #searchbar is not part of the DOM when you execute:

  // This will not work if #searchbar is not part of the DOM
  //   or if the DOM is not ready yet.
$("#searchbar").bind("onOptionsApplied", function () {
    alert("fdafds");
});

This type of stuff often happens if .bind() is outside the document ready or because #searchbar is added dynamically.

To make sure onOptionsApplied is bound correctly even under these conditions, use .live() or .delegate():

// This can be outside document ready.
//   It binds all now and future #searchbars
$("#searchbar").live("onOptionsApplied", function () {
    alert("fdafds");
});

// Document ready
$(function() {
    // Whatever you do....

    // Make sure #searchbar is now part of the DOM

      // Trigger onOptionsApplied
    $("#searchbar").trigger("onOptionsApplied");
    });
});

jsFiddle example

Peter Ajtai