views:

74

answers:

3

I want to call fillContent then later called beginEditingQuestion

fillContent(cid, "questions");
beginEditingQuestion(qid);

The problem is that I can't rung beginEfitingQuestion until all the ajax in fillContent is done. Is there an elegant way to delay the code? The only idea I can think of is to make a totally new function fillContentAndBeginEditingQuestion where I copy and paste fillContent into the new function and in the final ajax call add in beginEditingQuestion. This doesn't seem very elegant to me, I want to reuse fillContent in other contexts. What should I do?

+3  A: 

You can make fillContent take a callback parameter, and have it call the callback when it's done. Basically, you'd just add callback (); into the body of fillContent at the very end. In this way, you'd write something like this, and have the passed function executed at the end:

fillContent (cid, "questions", function () { beginEditingQuestion (qid); });
B.R.
A: 

It sounds like you need to change "fillContent" so that one of its parameters is a callback function that is invoked when the AJAX returns.

David
+3  A: 

I don't think you want to "slow", rather you want to wait for something to complete before the next piece of work is begun.

A pattern for this, used in many languages, is to use Events.

Conceptually:

You register an interest in a "DoneFillingContent" event, saying please call beginEditingQueue() when the event arrives.

fillContent has the repsonsibility of emiting an event to all interested parties. He doesn't realise what beginEditingQueue() does, it just a piece of work to be done on completion.

In the simplest version of the pattern, you just allow one callback function.

djna