Using MochiKit Deferred()

Oh my goodness I finally learned how to use MochiKit Deferred(). The piece of gold epiphany is the article Deferred Chains? in the MochiKit google newsgroup. Be sure to read Bob Ippolito’s post from march 21, 2006.


myfunc1 = function (poo) {
  log(‘myfunc1 poo is’, poo);
myfunc2 = function (goo) {
  goo += 2;
  log(‘myfunc2 goo is’, goo);
var foo = 0;
var squab = new Deferred();
squab.addCallback(myfunc1, foo);
squab.addCallback(myfunc2, foo);
//do a bunch of things whatever you want
foo = 10;
log(‘before callback foo is’, foo);


before callback foo is 10
myfunc1 poo is 11
myfunc2 goo is 12

The addCallback() function puts myfunc1 and myfunc2 on the “callback chain.” Callback chains are the subsequent operations that happen once a Deferred() gets completed via the callback() command. The callback functions execute in FIFO order therefore myfunc1 will complete before myfunc2 executes.

Adding the callback like with squab.addCallback(myfunc1,foo) passes foo as a parameter to myfunc1() at runtime. It translates to myfunc1(foo).

Common MochiKit AJAX operations like doXHR and loadJSONDoc both return Deferred objects. That allows you to add and chain callbacks for processing once your XMLHttpRequest returns from its call.

The FIFO callback chain is helpful because I previously created an AJAX call that had all the data that I wanted but needed to do some post-call things just a little bit differently. By adding a callback to the chain I will know that the first callback will be completed before I do my extra processing.

Using MochiKit doXHR with POST

This is a followup to my old post Using MochiKit doXHR using POST instead of GET.

The data that you send back in your controller will be stored in the Deferred object that gets returned. Look in the responseText field of the object.

var d = doXHR(url, 
   { method:‘POST’, 

The headers piece was the critical for the POST to work on my configuration.

Syndicate content