Reputation: 3145
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?
Upvotes: 0
Views: 1850
Reputation: 434665
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
:
function() { doPost() }
.GlobalEventBus.trigger("connection")
is triggered.GlobalEventBus.trigger('connected')
event.'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
.Upvotes: 2