Interpretation of jQuery. Callbacks source code

Source: Internet
Author: User
1 // StringtoObjectoptionsformatcache2varoptionsCache {}; 34 // ConvertString-formattedoptionsintoObject-formattedonesandstoreincache5/* 6 this... synt 1 // String to Object options format cache 2 var optionsCache = {}; 3 4 // Convert String-formatted options into Object-formatted ones and store in cache 5/* 6 this function mainly encapsulates the passed options String into an Object 7 For example, The passed 'Once memory 'is encapsulated into 8 optionsCache ['Once memory'] = {9 once: true, 10 memory: true 11} 12 so that the same options can be reused and judged next time 13 */14 function createOptions (options) {15 var object = optionsCache [options] = {}; 16 jQuery. each (options. split (core_rspace), function (_, flag) {17 object [flag] = true; 18}); 19 return object; 20} 21 22/* 23 * Create a callback list using the following parameters: 24*25 * options: an optional list of space-separated options that Will change how 26 * the callback list behaves or a more traditional option object 27*28 * By default a callback list will act like an event callback list and can be 29 * "fired" multiple times. 30*31 * Possible options: 32*33 * once: will ensure the callback list can only be fired once (like a Deferred) 34*35 * memory: will keep track of previous values and will call any callback added 36 * After the list has been fired right away with the latest "memorized" 37 * values (like a Deferred) 38*39 * unique: will ensure a callback can only be added once (no duplicate in the list) 40*41 * stopOnFalse: interrupt callings when a callback returns false 42*43 */44 jQuery. callbacks = function (options) {45 46 // Convert options from String-formatted to Object-formatted if needed 47 // (We check in cache first) 48 options = typeof options = "string "? 49 (optionsCache [options] | createOptions (options): 50 jQuery. extend ({}, options); 51 52 var // Last fire value (for non-forgettable lists) 53 // in most cases, this variable is an array containing two elements, [0] indicates the last called object, [1] indicates the last called parameter 54 memory, 55 // Flag to know if list was already fired 56 // identify whether the callback function has been executed, mainly used to implement once 57 fired, 58 // Flag to know if list is currently firing 59 // whether it is currently firing. Refer to the lock concept in multiline programming. It is mainly used to call the callback function and Line add, remove, or fire. There will be two separate examples to illustrate this situation: 60 firing, 61 // First callback to fire (used internally by add and fireWith) 62 firingStart, 63 // End of the loop when firing 64 firingLength, 65 // Index of currently firing callback (modified by remove if needed) 66 firingIndex, 67 // Actual callback list 68 // All callbacks will be pushed to this array 69 list = [], 70 // Stack of fire CILS for repeatable lists 71 // used in combination with firing, if there is on The ce option has no effect. Otherwise, when firing is true, add or fire operations are saved to this variable temporarily, so that the function queue 72 stack = In this variable can be processed when the list is cyclically completed! Options. once & [], 73 // Fire callbacks 74 fire = function (data) {75 // If memory is set to true, the parameter data is cached in memory, used to call 76 memory = options next time. memory & data; 77 fired = true; 78 // If options. memory is true, and firingStart is the last Callbacks. the length Value of the callback list after add is 79 firingIndex = firingStart | 0; 80 firingStart = 0; 81 firingLength = list. length; 82 firing = true; 83 for (; list & firingIndex <firingLength; firingIn Dex ++) {84 // if stopOnFalse is true and the callback function returned value is false, terminate the execution of the callback function queue 85 if (list [firingIndex]. apply (data [0], data [1]) ===false & options. stopOnFalse) {86 // set memory to false to prevent fire (this branch is triggered when stopOnFalse memory is called). 87 memory = false; // To prevent further callusing add 88 break; 89} 90} 91 firing = false; 92 if (list) {93 // options. once is false (for the role of stack, see) 94 if (stack) {95 // exist Recursion is possible, so while 96 if (stack. length) {97 fire (stack. shift (); 98} 99 // memory = true, memory = true case 100} else if (memory) {101 list = []; 102} else {103 // once = true, memory = false 104 self. disable (); 105} 106} 107}, 108 // Actual Callbacks object109 self = {110 // Add a callback or a collection of callbacks to the list111 add: function () {112 if (list) {113 // First, we save Current length114 var start = list. length; 115 (function add (args) {116 jQuery. each (args, function (_, arg) {117 var type = jQuery. type (arg); 118 if (type = "function") {119 // implement unique (callback is not unique or unique and does not exist, then push) 120 if (! Options. unique |! Self. has (arg) {121 list. push (arg); 122} 123 // if arg is an array, recursively Add the callback 124} else if (arg & arg. length & type! = "String") {125 // Inspect recursively126 add (arg); 127} 128}); 129}) (arguments ); 130 // Do we need to add the callbacks to the131 // current firing batch? 132 if (firing) {133 firingLength = list. length; 134 // With memory, if we're not firing then135 // we shocould call right away136 // if memory is not false, then, the system automatically fireworks} else if (memory) {138 firingStart = start; 139 fire (memory); 140} 141} 142 return this; 143 }, 144 // Remove a callback from the list145 remove: function () {146 if (list) {147 jQuery. each (arguments, function (_, arg) {148 var Indexes; 149 while (index = jQuery. inArray (arg, list, index)>-1) {150 list. splice (index, 1); 151 // Handle firing indexes152 // if you are executing Callbacks. when the remove operation is in the firing status, the values of firingLength and firingIndex are updated to 153 if (firing) {154 if (index <= firingLength) {155 firingLength --; 156} 157 // special processing. If the removed callback index is smaller than the index currently executing the callback, then, the unexecuted callback after firingIdex -- 158 // is executed normally. 159 if (index <= firingIndex) {160 firingIndex --; 161} 162} 163} 164}); 165} 166 return this; 167}, 168 // Control if a given callback is in the list169 has: function (fn) {170 return jQuery. inArray (fn, list)>-1; 171}, 172 // Remove all callbacks from the list173 empty: function () {174 list = []; 175 return this; 176}, 177 // Have the list do nothing anymore178 disable: function () {179 list = stack = memory = undefined; 180 return this; 181}, 182 // Is It disabled? 183 disabled: function () {184 return! List; 185}, 186 // Lock the list in its current state187 lock: function () {188 stack = undefined; 189 if (! Memory) {190 self. disable (); 191} 192 return this; 193}, 194 // Is it locked? 195 locked: function () {196 return! Stack; 197}, 198 // Call all callbacks with the given context and arguments199 fireWith: function (context, args) {200 args = args | []; 201 args = [context, args. slice? Args. slice (): args]; 202 if (list &&(! Fired | stack) {203 if (firing) {204 stack. push (args); 205} else {206 fire (args); 207} 208 return this; 209}, 210 // Call all the callbacks with the given arguments212 fire: function () {213 self. fireWith (this, arguments); 214 return this; 215}, 216 // To know if the callbacks have already been called at least once217 fired: function () {218 return !! Fired; 219} 220}; 221 222 return self; 223}; special note is that there is a firing variable. The application scenario of this variable is as follows: 1. In Callbacks. when firing is true in add, 1 // defines three callback functions to be added to the callback list: fn1, fn2, fn3 2 function fn1 (val) {3 console. log ('fn1 says '+ val); 4 // at this time, the firingLength In the Callbacks function will automatically add 1, although the initialized Callbacks object has the memory option, 5 // but add does not immediately execute fn2, but waits until the function queue before the add is executed before fn2 6 cbs. add (fn2); 7} 8 function fn2 (val) {9 console. log ('fn2 says '+ val); 10} 11 function fn3 (val) {12 console. log ('fn3 says '+ val); 13} 14 15 // Callbacks passed memory16 // you can also use $. callbacks ({memory: true}); 17 var cbs = $. callbacks ('memory '); 18 19 // add fn1 to the callback list. Because the add (fn2) operation is executed in fn1, the callback in the callback list is fn1, fn220 cbs. add (fn1); 21 22 // fn1 says foo23 // fn2 says foo24 cbs. fire ('foo'); 25 26 // pass the previous fire parameter to the recently added callback fn3, and execute fn327 // fn3 says foo28 cbs. add (fn3); 29 30 // run the fire command again. Note that the callback in the callback list is fn1, fn2, fn3, fn231 // fn1 says bar32 // fn2 says bar33 // fn3 says bar34 // fn2 says bar35 cbs. fire ('bar'); copy Code 2, in Callbacks. if firing is true in fireWith, copy the code function fn1 (val) {console. log ('fn1 says '+ val);} function fn2 (val) {console. log ('fn2 says '+ val); // at this time, the callback in cbs is not triggered immediately, but the [window, ['bar'] Put it into the stack. // After the function queue before fireWith is executed, cbs is executed. fireWith (window, ['bar']); // firingLength will be reduced by one. Be sure to remove the current function; otherwise, it will lead to an endless loop of cbs. remove (fn2);} var cbs = $. callbacks (); cbs. add (fn1); cbs. add (fn2); // fn1 says bar // fn2 says bar // fn1 says barcbs. fire ('bar ');
Related Article

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.