Wednesday, August 7, 2013

jQuery deferred

Hello fokes, it has been a while but finally here's another blog post :)

It all started with a project change in my company. I was cut of my standard Windows Forms (C# .NET) project and was put on a JavaScript jQuery mobile project. This scared the hell out of me because i'm a total n00b in JavaScript much less jQuery mobile. After refreshing my memory and digging up my old, ancient, JavaScript skills I started to work with JavaScript. After a while I had to program asynchronous operations to improve the usability of our mobile application.

The syntax and working of asynchronous operations in jQuery seemed a little bit strange to me. And that's why i like to dedicate a blog post to it. Lets start with a little bit of context. We develop our mobile application with TypeScript, and therefore work object orientated. The JavaScript below may seem strange to you, probably because its generated by the TypeScript compiler.

Lets say we a class Test. And that class has a method that may cost a lot of time to execute. You probably want that method to execute asynchronous. In order to do that you have to create a jQuery deferred. A deferred object has the ability to register multiple callbacks. A callback is a function that gets invoked when something is for instance done executing or failed. The longRunningAsyncOperation method in my example executes a task that lasts for 1000ms. The setTimeout performs the given function asynchronous and therefore immediately returns a deferred.promise(). The promise is a jQuery object that contains multiple callback options, such as fail, done, progress. When calling the longRunningAsyncOperation function we get the opportunity to register to the multiple callbacks of the promise. In my example i register to the done event.

No comments:

Post a Comment