简体   繁体   中英

How to wait for Backbone event trigger to complete before executing next line of code

I have a situation where I open a "connect to something" window, then do a POST request.

The way I do it is:

GlobalEventBus.trigger("connection")
doPost()

What happens now is: a connect window opens where I expect the user to enter the credentials and what not but the POST request is fired right after the window gets open.

I tried to put a while loop to check a boolean variable to see if it is completed, but that while loop gets fired even before the "connection" window gets opened.

I have no prior experience with UI or JavaScript stuff. How can I make this work?

You could use the optional arguments for trigger :

trigger object.trigger(event, [*args])
Trigger callbacks for the given event, or space-delimited list of events. Subsequent arguments to trigger will be passed along to the event callbacks.

So you could do this:

GlobalEventBus.trigger("connection", function() { doPost() });
// or
GlobalEventBus.trigger("connection", doPost);

and then the listener for the 'connection' event would grab the function out of its argument list and call it at the appropriate time. You'd have to be careful that only one listener called the passed callback function or modify the callback function so that calling it several times would only result in one doPost() call.

Alternatively, you could drop the 'connection' event entirely in favor of a simple function that hooks up the requisite callbacks:

app.getConnectionAnd(function() { doPost() });

then getConnectionAnd() would put up the dialog and attach the passed function to its "ok" callback. You could still fire the events if you had other uses for them but just because you have a general purpose event bus doesn't mean that you have to use it for everything.

If you really liked Backbone events you could rework your application do avoid this sequence:

GlobalEventBus.trigger("connection");
doPost();

Instead, you could add another event that triggers doPost :

  1. Note somewhere globally accessible that you want to call function() { doPost() } .
  2. GlobalEventBus.trigger("connection") is triggered.
  3. Someone listening for the above throws up the dialog asking for connection details.
  4. The dialog establishes the connection and triggers a GlobalEventBus.trigger('connected') event.
  5. Someone listening for the 'connected' event looks up what is supposed to be called, notices that it is the function from (1), calls it, and resets the function-to-call to undefined .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM