jQuery 1.5 adds "Deferred Objects". What are they, and what exactly do they do?
相关问题
- How to fix IE ClearType + jQuery opacity problem i
- jQuery add and remove delay
- Include empty value fields in jQuery .serialize()
- Disable Browser onUnload on certain links?
- how to get selected text from iframe with javascri
While working in Javascript, we encounter situation where function calls are asynchronous. That is the calee function's (let say X) flow does not wait for the called asynchronous function (Let say Y). Typical example is when we make calls to a server to fetch some data from a database or an HTML page. If those calls were not asynchronous, the user interface will be stuck waiting for the server to respond. This asynchronous nature leads to a problem when you want to execute things in an order, for example, you want to print something after Y (asynch) is done executing or done fetching data. Here jQuery provide us with Deffered Object. Basically, jQuery has taken care of all boilerplate code that usually we write to resolve this situation. Here is a simple example:
You can write your own deferred (asynch) function
I hope this helped.
Deferred Object
As of jQuery 1.5, the Deferred object provides a way to register multiple callbacks into self-managed callback queues, invoke callback queues as appropriate, and relay the success or failure state of any synchronous or asynchronous function.
Deferred Methods:
Deferred In Action:
And it seems that the existing ajax() method callbacks can be chained rather than declared in the settings:
Working Example From Eric Hynds blog post: http://jsfiddle.net/ehynds/Mrqf8/
jqXHR
As of jQuery 1.5, the $.ajax() method returns the jXHR object, which is a superset of the XMLHTTPRequest object. For more information, see thejXHR section of the $.ajax entry
Correct me if i'm wrong, but it recently clicked for me that it's essentially an Asynchronous Task Runner. The promise is a result contract, ensuring you receive ...something, but without guarantee of when you'll get it.
Rather then telling you what it does, I'll show you what it does and explain it.
A copy of the related source of jQuery 1.5 with annotating explaining what it's doing. I think the comments are mostly correct.
This may be of benefit