Home  >  Article  >  Web Front-end  >  [Javascript] zepto source code Callback analysis

[Javascript] zepto source code Callback analysis

php是最好的语言
php是最好的语言Original
2018-08-06 15:21:181611browse

The Callback module is used to manage callback functions and is also the basic part of the deferred delay object. Now let’s take a look at its source code.
Optional parameter:

  Options:
    once: 是否最多执行一次,
    memory: 是否记住最近的上下文和参数
    stopOnFalse: 当某个回调函数返回false时中断执行
    unique: 相同得回调只被添加一次

This is an optional parameter, you can test it below:

var a = function (value) {
  console.log('a:' + value);
};
var b = function (value) {
  console.log('b:' + value);
};
var callbacks = $.Callbacks();
callbacks.add(a);
callbacks.fire(['hello']);
callbacks.add(b);
callbacks.fire('中');

The following is his output result:

a: hello,
a:中,
b:中

You can see Yes, when we fire for the second time, function a will also be executed.
When adding parameters for experiments, first add memory

var callbacks = $.Callbacks({
  memory: true
});
callbacks.add(a);
callbacks.fire('hello');
callbacks.add(b);
输出:
a:hello,
b:hello

Add memory parameters. Memory records the last time the callback function was triggered. Functions added thereafter will be executed immediately using this parameter. Looking at the use of once

var callbacks = $.Callbacks({
  once: true
});
callbacks.add(a);
callbacks.fire('hello');
callbacks.fire('中');
输出:
a:hello

, we can see that although the fire method is executed twice, the result is only output once. The other two parameters are easy to understand, so you can try the details yourself.

$.Callbacks = function(options) {
  options = $.extend({}, options)
  var memory, 
    fired, 
    firing,
    firingStart,
    firingLength,
    firingIndex,
    list = [],
    stack = !options.once && []
}

Let’s take a look at the meaning of each parameter. memory will remember the last triggered context and parameters in memory mode. fired means whether the callback has been triggered. Firing means that the callback is being triggered. The firingStart callback task starts. Position, firingLength, the length of the callback task, firingIndex, the index of the current callback, and list represents the real callback queue. If it is not triggered once, it is used to cache the task parameters that are not executed during the triggering process.

fire = function(data) {
  memory = options.memory && data
  fired = true
  firingIndex = firingStart || 0
  firingStart = 0
  firingLength = list.length
  firing = true
  for ( ; list && firingIndex < firingLength ; ++firingIndex ) {
    if (list[firingIndex].apply(data[0], data[1]) === false && options.stopOnFalse) {
      memory = false
      break
    }
  }
  firing = false
  if (list) {
    if (stack) stack.length && fire(stack.shift())
    else if (memory) list.length = 0
    else Callbacks.disable()
  }
}

The fire function is the only built-in function. Its function is to trigger the callback execution of the list. First, take a look at the parameters it passes in. It is not the same as the fire we call $.Callbacks externally. , data here is an array, data[0] represents the context, data[1] is the parameter of the method call. Then there is the initialization of each parameter. memory means that if options.memory is true, save the data, fired is true, if firingStart is 0, then firingIndex is 0, firingStart is set to 0, and the firing callback mark firing is true.
Then traverse the callback list and execute the callbacks one by one. The if judgment inside this means that if the callback function returns false and options.stopOnFalse is false, the memory cache will be cleared. After the traversal is completed, change the execution status to false. If the list exists and the stack also exists, take out the task parameters and call the fire function to execute. If memory exists, clear the list, otherwise perform callback execution.

Finally, this file returns Callbacks. Let’s take a look at its specific implementation:

Callbacks = {
  add: function () {
    if (list) {
      var start = list.length,
        add = function (args) {
          $.each(args, funciton(_, arg) {
            if (typeof arg === &#39;function&#39;) {
              if (!options.unique || !Callbacks.has(arg)) list.push(arg);
            } else if (arg && arg.length && typeof arg !== &#39;string&#39;) add(arg);
          })
        }
      add(arguments)
      if (firing) firingLength = list.length;
      else if (memory) {
        firingStart = start;
        fire(memory)
      }
    }
    return this;
  }
}

The main function of this function is to act like a list There is a push callback inside. First, determine whether the list exists. If it exists, start is assigned the length of the list, and an add method is added internally. The internal add method is mainly to add a callback to the list. If the parameter we pass in is an array, the add method is called again. Then call the add method and pass the arguments in. If the callback is in progress, the length of the callback task, firingLength, is the length of the current task list so that the callback function added subsequently can be executed. If memory exists, set the start to the first position in the newly added list, and then call fire.
Let’s take a look at how fireWith works:

fireWith: function(context, args) {
  if (list && (!fired || stack)) {
    args = args || [];
    args = [context, args.slice ? args.slice() : args];
    if (firing) stack.push(args);
    else fire(args);
  }
  return this;
}

The parameters passed in include context and parameter list. The condition for function execution is that the list exists and the callback is not executed or the stack exists, and the stack can be empty. First, reassign args. args[0] is the context and args[1] is the copied list. If the callback is in progress, add args to the stack, or just execute args.

Related articles:

Introduction to the Gesture module in the Zepto source code

A brief analysis of the Callback method in Javascript

The above is the detailed content of [Javascript] zepto source code Callback analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn