Jquery.callbacks () callback function queue usage detailed _jquery

Source: Internet
Author: User

The example in this article describes the Jquery.callbacks () callback function queue usage. Share to everyone for your reference, specific as follows:

1, Jquery.callbacks

The Jquery.callbacks () function, introduced in version 1.7, returns a multi-purpose object, provides a powerful way to Manage callback lists. It supports adding, removing, firing, and disabling callbacks.

The $. The callbacks () function is internally used to provide the base functionality behind the JQuery $.ajax () and $. Deferred () components. It can be used as a similar base to define functionality for new components.

Next, we look at the next four standard control flags.

1.1 Once

The callbacks object created is only allowed to be firewith () once [Note: Method Fire () is the appearance mode of Firewith ()].

var callbacks = $. Callbacks ("Once");
Callbacks.add (function () {Console.log ("F1");});
Callbacks.fire (); Output "F1"
callbacks.fire ();//Nothing happens, in the source code has been disabled list.disable ()

1.2 Memory

When the Add () method is invoked, if the callbacks queue satisfies the fired && firing = False (True execution) && memory (which needs to be specified in the constructor), the callback function in the Add () is executed immediately , and the parameter in the call to the add callback function is stored in the memory variable. The memory variable is used to store the parameter [context, arguments] that was used when the last call to Callbacks.firewith (...) was made.

If the Callbacks object is created with the "memory" flag as it argument, additional functions may be added and fired Er the callback list is locked.

$ (function ($) {
    var callbacks = $. Callbacks ("Memory");
    Callbacks.add (function () {Console.log ("F1");});
    Callbacks.fire (); Output "F1", when the list of functions has been executed!
    Callbacks.add (function () {Console.log ("F2");});  Memory function Here, there is no fire, the same results: F2
    callbacks.fire ();//re-fire once, output F1 F2. Firingstart = 0
    //once with
    callbacks = $. Callbacks ("Once Memory");
    Callbacks.add (function () {Console.log ("F3");});
    Callbacks.fire (); Output "F3", when the list of functions has been executed!
    Callbacks.add (function () {Console.log ("F4");});      No fire, same results: F4
    Callbacks.fire ();//due to "once", nothing will be done here
});

1.3 Unique

Whether a function in the list of callback functions can be duplicated, which is related to the Add () method, avoids adding multiple identical callback functions to the list of callback functions.

var f1 = function () {Console.log ("F1");
var callbacks = $. Callbacks ();
Callbacks.add (F1);
Callbacks.add (F1);
Callbacks.fire (); Output F1 F1
//pass parameter "unique"
callbacks = $. Callbacks ("unique");
Callbacks.add (F1); Effective
Callbacks.add (F1);//Add Not in
callbacks.fire ();//output: F1

1.4 Stoponfalse

By default, when the Firewith () method is executed, all functions in the entire callback function list are executed sequentially, but if Stoponfalse is set, the function that follows will no longer execute when a function returns FALSE. Even if you set the memory, the added function does not execute, that is, once a function returns false, the memory feature is disabled. But if "Once" is not set, calling fire again can trigger the callbacks again.

var f1 = function () {Console.log ("F1"), return false}; Note return false;
var F2 = function () {Console.log ("F2");
var callbacks = $. Callbacks ();
Callbacks.add (F1);
Callbacks.add (F2);
Callbacks.fire (); Output f1 F2
callbacks = $. Callbacks ("Memory Stoponfalse");
Callbacks.add (F1);
Callbacks.add (F2);
Callbacks.fire (); Output only F1
Callbacks.add (function () {Console.log ("F3");});//No output, memory has been lost
callbacks.fire ();//re-triggered, Output F1

2. Memory Callback Queue

var i = 0;
var inc = function (s) {
 i++;
 Alert (i + "$" + s);
};
var callbacks = $. Callbacks (' memory ');
Callbacks.add (function iteral () {
 callbacks.add (inc);
 if (I <= 1) {
  callbacks.fire (i);
 }
});
Callbacks.fire (i);
Callbacks.add (inc.);
/* list = [];
list = [it];
--->fire (0), i=0
1, list = [it, Inc]
2, push (Fire (0))
3, i++ [Inc (0)] (i=1)
shift ()--->fire (0 ), I=1
1, list = [It, Inc, Inc.];
2, Push (Fire (1)),
3, i++ [Inc (0)]
4, i++ [Inc (0)] (i=3)
shift ()--->fire (1), i=3
1, list = [It, Inc , Inc, Inc];
2, I++ [Inc (1)]
3, i++ [Inc (1)]
4, i++ [Inc (1)] (i=6)
--->add (inc), I=6, memory=[this,1]
1, i++ [ Inc (1)] (i=7)
* *

3, Jquery.callbacks source code

Explanation: In order to facilitate understanding, modified part of the source code, reduced some features ~ ~ ~

Jquery.callbacks = function (options) {//String--> Object Improvement Recommendation: Set the parameters that are not configured by default to False instead of undefined.
  Easy to read and control programs. options = Optionscache[options] | |
  CreateOptions (options); 
    var firing, memory,//last fire value [context, Args] (for memory lists) fired, Firinglength, Firingindex, Firingstart, list = [], stack = Options.once = = true?
      False: [],//Stack of Fire calls for repeatable lists fire = function (data) {//Data--> [context, args] Memory =!! Options.memory && data;
      False OR [context, arguments] fired = true; Firingindex = Firingstart | |
      0;
      Firingstart = 0;
      Firinglength = List.length;
      firing = true;
      The list is placed in the conditional judgment because executing the callback function may change the state of the list, such as this.disable (). for (; list && Firingindex < firinglength firingindex++) {if (list[firingindex].apply (data[0), data[ 1] = = = False && Options.stoponfalse = = true) {memory = false;//disable memory function, so call aDD () Adds a new callback function that does not automatically call the break immediately;
      } firing = false; if (list) {if (stack) {//Enter condition: fired && firing = = False && stack, implement recursive call if (  Stack.length) {Fire (Stack.shift ());//[[Context1, Arguments1], [Context2, Arguments2]]} else if (memory) {//Enter condition: fired && firing = = False && stack = = undefined && memory field
        (memory variable can only be modified by the fire () function)//here list = [], mainly for performance optimization, in case the object is not executed for a long time, occupy the system memory list = []; else {//Enter condition: Fired && firing = false && stack = = undefined && no memory field, indicating the need to keep
        The necessary self.disable ();
          The self = {add:function () {if (list) {//}}, this condition should be bound by almost all APIs because we need to process the queue
          var originlength = list.length;
               Jquery.each (arguments, function (_, arg) {if (Jquery.type (arg) = = "function") { // (! (Options.unique && Self.has (ARG))
                The role of the unique field if (!options.unique | |!self.has (ARG)) {List.push (ARG);
          }
            }
          }); if (firing = = True) {//Enter Condition: Description is executing the callback function queue, and the currently executing callback function activates the Add () function to maintain the loop boundary in time Firinglength = List.le
          Ngth;
            else if (memory) {//Enter condition: Memory && fired && firing = = False, indicating that the previous fire () behavior has completely ended
            Firingstart = Originlength;
          Fire (memory);
      } return this; }, Remove:function () {if (list) {Jquery.each (arguments, function (_, arg) {var las
            Tindex;
              while ((lastindex = Jquery.inarray (arg, list, lastindex)) >= 0) {list.splice (lastindex, 1);
                  if (firing = = True) {//update boundary condition in time, implement intelligent process if (lastindex <= firinglength) {
                firinglength--;
    }            if (lastindex <= firingindex) {firingindex--;
        }
              }
            }
          });
      return to this; }, the Has:function (func) {//API has two functions, and according to a single duty point of view, a isnotempty () interface (Non-empty) return func should be added. Jquery.inarray (Fu NC, List) >-1:!!
      (list && list.length);
        }, Empty:function () {list = [];
      return this;
        }, Disable:function () {///Disable the object completely, stack disabled, memory disable list = stack = memory = undefined;
      return this;
      }, Disabled:function () {return!list;
        }, Lock:function () {stack = undefined;
        If the memory does not store the call state, disable the object directly (it may be locked without calling, or there is no memory field) if (!memory) {self.disable ();
      return to this;
      }, Locked:function () {return!stack; }, Firewith:function (context, args) {args = args | |
        [];
  var data = [context, args];      if (list && (fired = = False | | stack) {if (firing) {//Enter condition: firing = = True &&      Stack description The callback function queue Stack.push (data) is currently executing; Stack is actually a queue structure, here with stack some confusion} else {/Enter condition one: firing = = False && fired = = False description never No Fire () Cross//Enter conditions two: firing = = False && fired = = true && stack = [] Description called at least once, and currently allow multiple calls, you can pass the lock ()
          Locking fire (args);
      } return this;
        }, Fire:function () {Self.firewith (this, arguments);
      return this; }, Fired:function () {return!!
      Fired;
  }
    };
return self;

 };

4, Cranky

The core of the Jquery.callbacks () method is the fire () method, which encapsulates the fire () method in a function that is not directly accessible, so such states as memory, firing, fired are not changed for the external context.

Also note that if the This object is used in the callback function, you can use this to access the public API of the Self object directly. Of course, you can also use Firewith () to specify the reference object for this.

The core idea of Jquery.callbacks () is the PUB/SUB model, which establishes loose coupling and efficient communication between programs.

More interested readers of jquery-related content can view the site topics: "jquery common Plug-ins and Usage summary", "jquery Ajax Usage Summary", "jquery table (table) Operation Tips Summary", "jquery drag and drop effects and tips summary", " jquery Extended Skills Summary, jquery Common Classic effects summary, jquery animation and special effects usage summary and jquery selector Usage Summary

I hope this article will help you with the jquery program design.

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.