Front-end programs to improve travel (ix)----lingering objects

Source: Internet
Author: User
Tags openid

recently, the internal referral program when entering the project homepage. In accordance with previous habits, the code that should be called after the interface should be run. Put the AJAX request inside the success to run. Of course it can. However, the organization and readability of the code are not that high.

The concept of deferred object (lingering objects) was discovered by looking at the jquery official website API.

first, the translation of API documents:

Lingering objects, which are introduced in jquery1.5. Is a chain-function object that is generated by calling the Jquery.deferred () method. It is able to register multiple callbacks to the callback queue. Extracts the callback queue, passing either the success or failure state of any asynchronous or synchronous function.
The lingering object is a chain-type. A chain similar to a jquery object, but it has its own method. After creation, you can use whatever is involved in the following method, whether it is a direct chain call or not. Or save this object to a variable. And one or more methods are raised in this variable.

    • Deferred.always ()
joins the action method, regardless of whether the lingering object is in the resolved state or the deny state is called.


    • Deferred.done ()
Join the action method, only the lingering object is in the resolved state to be called
    • Deferred.fail ()
Join the action method, only the lingering object is in the denied state will be called
    • Deferred.isrejected ()
Infer whether a deferred object is in a rejected state
    • Deferred.isresolved ()
infers whether a lingering object is in the resolved state.


    • Deferred.notify ()
invokes the in-progress callback on the deferred object of a given variable.
    • Deferred.notifywith ()
invokes the in-progress callback on the deferred object for a given variable and context.
    • Deferred.pipe ()
Utility method used to filter and OR or chain delay
    • Deferred.progress ()
The join operation is called when the deferred object generation is notified.


    • Deferred.promise ()
Returns the deferred promise object.


    • Deferred.reject ()
rejects a lingering object and invokes a failed callback regardless of the given number of parameters.
    • Deferred.rejectwith ()
rejects the callback object, invoking the failed callback regardless of the given context and parameters.
    • Deferred.resolve ()
resolves a lingering object, and invokes the completion callback regardless of the given number of parameters.
    • Deferred.resolvewith ()
Resolves a lingering object and invokes the completion callback regardless of the given context and number of parameters.


    • Deferred.state ()
infers the current lingering object state.
    • Deferred.then ()
The method is called when the deferred object is resolved, rejected, or in progress.
    • Jquery.deferred ()
The constructor for the deferred object.


    • Jquery.when ()
provides a way to run a callback function based on one or more objects. Callback functions are often deferred objects that represent asynchronous events
    • . Promise ()
Returns a Promise object when all the bindings to the collection, queue, or no action are finished.


Second, delay object analysis and use:

It is not difficult to draw conclusions. The above API includes the construction of delay object, the method of delay state setting, and the monitoring method of delay state.


Data structures for deferred objects

Lingering objects contain three states:resolved (Resolved), rejected (not resolved), progress (in progress).

These three states can be viewed in real time with the deferred object state method.


Deferred object Status View

Lingering objects are the way that jquery's callback functions are resolved. The delay, as the name implies, is to defer to some point in the future, similar to the delay method in the jquery animation function, except that the latter is a fixed time delay. Lingering objects are the time when the deferred run is inferred from a fixed state.

var DTD = $. Deferred (); Create a new deferred object var wait = function (DTD) {var tasks = function () {alert ("Run complete!

"); Dtd.resolve ();    Change the running state of the deferred object};    SetTimeout (tasks,5000);  return DTD; };$.when (Wait (DTD)). Done (function () {alert ("haha. It worked!

"); })  . Fail (function () {alert ("Error! "); });


The above code runs the flowchart:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvewluz3lpbgvkaq==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center ">


in the code example above, the deferred object is defined as a global object, which causes a delay state. Be able to make changes at any time.

one way to improve:

var DTD = $. Deferred (); Create a new deferred object var wait = function (DTD) {var tasks = function () {alert ("Run complete!      "); Dtd.resolve ();    Change the running state of the deferred object};    SetTimeout (tasks,5000); return Dtd.promise ();  Returning the Promise object, the Promise object is only open to state-independent methods, that is, the three state methods are not open and cannot be set}; var d = Wait (DTD); Creates a new D object. Instead, manipulate the object $.when (d). Done (function () {alert ("Haha, success!

"); })  . Fail (function () {alert ("Error!

"); }); D.resolve (); At this time This statement is not valid.


  The above code, in the Wait function, returns a value that is a promise object. It is not difficult to find out by promise object data structure that the Promise object has all the methods of delaying the object except the change state method, that is, thepromise object cannot change the running state, so that the external changes to the state can be prevented. data structures for promise objects


Improvement Method Two:

Constructs a deferred object into a local variable inside a function. This allows for better encapsulation and prevents external changes to the state.

var wait = function (DTD) {var DTD = $. Deferred (); Inside the function. Create a new deferred object var tasks = function () {alert ("Run complete!      "); Dtd.resolve ();    Change the running state of the deferred object};    SetTimeout (tasks,5000); return Dtd.promise ();  Returns the Promise object}; $.when (Wait ()). Done (function () {alert ("Haha, success!

"); })  . Fail (function () {alert ("Error!

"); });


Improvement Method Three:

Directly use the function name as $. Deferred () The number of references passed in,$. The deferred object generated by Deferred () is passed into the function as a wait function argument.

var wait = function (DTD) {var tasks = function () {alert ("Run complete.      "); Dtd.resolve ();    Change the running state of the deferred object};    SetTimeout (tasks,5000); return Dtd.promise (); Returns the Promise object}; $. Deferred (Wait). Done (function () {alert ("Haha, success! "); })  . Fail (function () {alert ("Error! "); });

$. Deferred () mode run State


third, the use of the project:

Yue Timor uses another method in an inline project, which is to define the deferred object as a local variable. and returns the Promise object. Here promise objects and lingering objects cannot change state. The recording and monitoring methods for the delay state are the same.

function Loadinternalhost () {            var DTD = $. Deferred ();               Dtd.resolve ();            return dtd.promise ();//Returns a deferred object on the original Defferred object, and two objects will record the original deferred object state, but the latter cannot change the state. Other methods consistent        }



Promise record of the delay status

When two interfaces are called separately, the delay listener function agrees to specify a callback for multiple events.

For example, the following code, respectively, to obtain the inner push of the city and the two parts of the announcement data, the operation might load data action.

$.when (Getinternalrecommendcitys (), Getcomment ()). Done (function () {getinternalrecommendjobadlist (Oldsearc            Hdata.keyword, Oldsearchdata.locid); }); function Getinternalrecommendcitys () {var DTD = $.            Deferred ();                $.ajax ({type: "Get", data: {"OpenID": OpenID}, DataType: "JSON", url: ".. /api/internalinfo/internalrecommendcitys ", success:function (data) {$city = $ (" #citySe                    Lect ");                        for (var i = 1; i < data.length; i++) {$str = $ ("<option></option>");                        $str. Text (data[i].name);                        $str. Val (Data[i].value);                        $city. Append ($STR);                    Dtd.resolve ();               }//Import the optional city to the select list}, Error:function () {dtd.resolve (); }            });        return Dtd.promise (); } function Getcomment () {var DTD = $.            Deferred ();                $.ajax ({type: "Get", data: {"OpenID": OpenID}, DataType: "JSON", url: ".. /api/internalinfo/getcomment ", success:function (data) {$ (". Notice-content pre "). HTML (                    Data.data);                Dtd.resolve ();                }, Error:function () {dtd.resolve ();        });//Get Data Publication return Dtd.promise (); }


Front-end programs to improve travel (ix)----lingering objects

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.