1

I am writing a plugin which emits the events activating and activated. I want to trigger the event activated only when all event handlers of activating are executed. I know that $.trigger() calls the event handlers synchronously, but the problem is I may have some async code in my event handler:

Example:

$("test").trigger("activating");
$("test").trigger("activated");


$("test").on("activating",function()
{
     $.post("/test",{data:"test"},function()
    {
            //dom modifications here
            ////////////////
            //Here I would like to notify that the event handler is finished, like maybe async.js
    }
});

I have a few clues about $.Deferred & Promises, but I don't see how to implement them to resolve my specific problem.

Could somebody here give me the solution?

Thanks

lebolo
  • 2,120
  • 4
  • 29
  • 44
  • Event listeners do not have any return values. They do not signal anything back to the event source through the event (apart from `preventDefault()`). – Bergi Apr 30 '14 at 14:25
  • I think what you want is to move the `activated` trigger into the ajax success function. That way, the activated event will be triggered when your ajax call is complete. – HashFail Apr 30 '14 at 15:04
  • If you have async code in your event handlers, then you cannot solve this issue without those event handlers participating in the solution. If they have async code, they will have to at least do something like register a promise that will indicate when they are done. – jfriend00 Apr 30 '14 at 15:56
  • Oddly enough not even an hour later someone has ask the same question: http://stackoverflow.com/questions/23392924/design-pattern-for-waiting-on-asynchronous-event-handlers – Bergi Apr 30 '14 at 16:08
  • Thank you, i have read that post and it seems to answer my question. I will test it soon , and if it does, i'll repost it and tag it as the solution – user2799445 May 09 '14 at 16:33

0 Answers0