Mailing List Archive

jQuery.Deferred: introducing the Promise pattern to client-side async modules?
I noticed this commit during code review:

https://www.mediawiki.org/wiki/Special:Code/MediaWiki/107350

this adds a module providing mw.Api.watch() and mw.Api.unwatch() functions
as handy wrappers around calling the MediaWiki API methods. Each takes
three parameters:

* title
* success callback
* error callback

There's a lot of such things; and it tends to get a bit ugly to keep track
of if making a lot of similar calls.


We may wish to consider using the "promise" pattern, which is available in
jQuery's "Deferred" class -- already used on things like $.ajax behind the
scenes.

Instead of passing pairs of callbacks around all the time, under the
Promise pattern, an async function can return an object to which success
callbacks can be attached. The advantage of this over explicitly passing
callbacks is that the whole state can be bundled in one item -- this can
make things easier to deal with when working with several items at once,
such as starting off a couple queries, then waiting until they all come
back.

A simple call looks fairly similar; using raw callback params:

mw.Api.watch('some title', function() {
// success!
}, function() {
// error!
});

using a $.Deferred promise:

mw.Api.watch('some title').then(function() {
// success!
}).fail(function() {
// error!
});

In many cases, code like in the mw.Api modules could probably just get the
promises 'for free' by passing through to $.ajax and returning the return
value, eliminating some of the boilerplate for passing callbacks around.
You also get benefits from functions like $.when() allowing to collect
several async tasks together...


There's a nice intro, overview, and jQuery-flavored examples on this blog
post:
http://msdn.microsoft.com/en-us/scriptjunkie/gg723713


Let's not go rewriting things for 1.19 ;) but it may be worth looking
through some more of what jQuery gives us as we design more front-end code
for 1.20 and beyond ...

-- brion
_______________________________________________
Wikitech-l mailing list
Wikitech-l@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/wikitech-l
Re: jQuery.Deferred: introducing the Promise pattern to client-side async modules? [ In reply to ]
Hey,

This is cool stuff :)

And now we got our first MediaWiki example AFAIK:

*
https://svn.wikimedia.org/viewvc/mediawiki/trunk/extensions/EducationProgram/resources/ep.api.js?r1=109015&r2=109014&pathrev=109015
*
https://svn.wikimedia.org/viewvc/mediawiki/trunk/extensions/EducationProgram/resources/ep.instructor.js?revision=109015&view=markup&pathrev=109015

Cheers

--
Jeroen De Dauw
http://www.bn2vs.com
Don't panic. Don't be evil.
--
_______________________________________________
Wikitech-l mailing list
Wikitech-l@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/wikitech-l