Cómo esperar a que se complete el desencadenante del evento Backbone antes de ejecutar la siguiente línea de código

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

La forma en que lo hago es:


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?

preguntado el 01 de febrero de 12 a las 03:02

1 Respuestas

You could use the optional arguments for trigger:

detonante 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.

Entonces podrías hacer esto:

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() llamada.

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

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

luego 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:


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") se activa
  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') evento.
  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.

Respondido el 14 de Septiembre de 13 a las 13:09

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.