Home >Web Front-end >JS Tutorial >What's the point of using Callbacks in jQuery?

What's the point of using Callbacks in jQuery?

伊谢尔伦
伊谢尔伦Original
2017-06-16 14:43:541178browse

Callbacks is a method introduced in jQuery 1.7, which is used to manage a group of callback functions with the same method parameters. In addition to adding, deleting, and clearing callbacks like arrays, Callbacks also provides several special modes. In different modes, the life cycle and execution order of callback functions are slightly different.

Generate callback column (Callbacks)

var callbacks = $.Callbacks(flags);

The parameter falgs is a string, used to indicate the mode of Callbacks. For example, in the "once stopOnFalse" mode, the callback will only be executed once at most. If the execution process If one of the callbacks returns false, the execution of the callback column will also be interrupted.

So where are the usage scenarios of jQuery.Callbacks?

In many cases it is necessary to control the sequential execution of a series of functions. Then generally a queue function is needed to handle this problem

Let's look at a piece of code

function Aaron(List, callback) {
    setTimeout(function() {
      var task = List.shift();
      task(); //执行函数
      if (task.length > 0) {  //递归分解
        setTimeout(arguments.callee, 1000)
      } else {
        callback()
      }
    }, 25)
  }
  Aaron([function(){
    alert('a')
  },function(){
    alert('b')
  }],function(){
    alert('callback')
  })
 
分别弹出 ‘a’ , ‘b’ ,’callback’

Pass in a set of function parameters, parse them recursively, and execute them one by one. In fact, you can use setTimeout to save the function The principle of executing only after adding to the end of the queue

*****But is it troublesome to write like this? *****

Let’s switch to the method provided by jQuery

var callbacks = $.Callbacks();
  callbacks.add(function() {
    alert('a');
  })
  callbacks.add(function() {
    alert('b');
  })
  callbacks.fire(); //输出结果: 'a' 'b'

Is it much more convenient and the code is very clear, so it is a multi-purpose callback Function list objects provide a powerful way to manage callback function queues.

Also provides several convenient processing parameters

once: Ensure that this callback list is only executed (.fire()) once (like a deferred Deferred).

memory: keep the previous value, the latest value added to the back of this list will be executed immediately if any callback is called (like a Deferred).

unique: ensures that only one callback can be added at a time (so in the list There are no repeated callbacks).

stopOnFalse: When a callback returns false, interrupt the call

var callbacks = $.Callbacks('once');
  callbacks.add(function() {
    alert('a');
  })
  callbacks.add(function() {
    alert('b');
  })
  callbacks.fire(); //输出结果: 'a' 'b'
  callbacks.fire(); //未执行

once’s function is to make the callback queue execute only once

Callbacks Mode

Default mode: The callbacks in the callback column can be executed multiple times by default, and the callback functions can be added repeatedly. But during execution, the newly added callback is not executed.

once: Each callback in the column is executed at most once. After the execution is completed, the callback function column is cleared.

memory: During the callback execution process, if a new callback is added, the new callback can also be executed.

Unique: The same callback cannot be added repeatedly.

stopOnFalse: If a callback returns false, subsequent callbacks will not be executed, even in memory mode.

var callbacks = $.Callbacks("once memory");

Callback execution order

The callbacks are saved in the array and then traversed through the for loop, so the callbacks in the column are executed in the order they are added, and the last one added is generally executed last.

// Fire the items on the list
var foo = function( value ) {
  console.log( "foo:" + value );
};
// Add another function to the list
var bar = function( value ){
  console.log( "bar:" + value );
};
var callbacks = $.Callbacks();
callbacks.add( foo );
callbacks.add( bar);
callbacks.fire("hello"); 
// output: foo: hello
// output: bar: hello

The only exception is if the mark is memory and if fire() has been called before, then the new callback will be executed immediately using the parameters of the previous fire after it is added by add(). However, the callback called by fire() before add() will not be executed again immediately if fire() or fireWith() is not used.

Other key points

Calling Fire() or fireWith() of Callbacks in the callback function

There is a situation where it is called again in the callback Callbacks object's fire() or fireWith() method, what should I do in this case?

Jquery does this: call fire() or fireWith() in the callback, the Callbacks object just saves the parameters of fire() or fireWith(), and does not immediately execute the callback in the column. After all callbacks in callbacks have been executed, re-execute all callbacks in the Callbacks object with new parameters.

Note: If the mark is once, executing fire or fireWith() in the callback is invalid.

function fn1( value ){
   console.log( value );
 
   if (value == "bar!") return false;
 
   callbacks.fire("bar!");
}
 
function fn2( value ){
  console.log( "fn2 says: " + value);
}
 
var callbacks =$.Callbacks("stopOnFalse");
 
callbacks.add( fn1 );
callbacks.add( fn2 );
 
// Outputs: foo!
// Outputs: fn2 says:foo!
// Outputs: bar!
callbacks.fire("foo!" );

After calling callbacks.disable(), callbacks can no longer be enabled

After calling disable(), the callback function list will be cleared. At this time, using fire or fireWith will not work. Any response. Therefore, Callbacks does not provide an enable method because all callbacks have been cleared and there is no need to enable them again.

callbacks.lock()

The callback column is locked, and calling callbacks.fire() or callbacks.fireWith() will be invalid.

If callbacks.lock() is called in a callback, there is one thing to note:

callbacks have a memory tag: there are no callbacks executed in the current fire() or fireWith() method. Execution will continue, but callbacks.fire() and callbacks.fireWith() in the callback will no longer work.

Callbacks have no memory tag: all callbacks are cleared, which means that subsequent callbacks will no longer be executed.

The strange thing is that Callbacks do not provide an unlock method. That is to say, once locked, Callbacks permanently lose the ability to call fire() or fireWith().

The above is the detailed content of What's the point of using Callbacks in jQuery?. 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