This article, part 3 of the jQuery Source Code Analysis of Js Programming Techniques, introduces the Callback module. It is essentially an observer (subscriber) design pattern. How is this mode implemented in jQuery? What are the core concepts, this paper will do discussion, not exhaustive, but for clear and easy to understand, to attract jade.

How to use

Add the observer, and then notify the observer with.fire

const cb = $.Callbacks()
cb.add(function(msg){
  console.log("first add: " + msg)
})
cb.add(function(msg){
  console.log("second add: " + msg)
})
cb.fire("hello")
//output
//"first add: hello"
//"second add: hello"
Copy the code

Introduction to Important Concepts

Initialize the

  • $.CallbacksThe factory function performs initialization and returns a assembled CB object
  • list: a list of added observers (functions)
  • queue: A queue stores the body of the message to be executed
  • locked: Records the lock status of the cbObj object
  • fireInternal function that notifies all observers of the message body in the queue (function)
  • cbObj: returns an object that exposes a series of methods

Exposes methods

  • addAdd the observer function to the list array
  • remove: Removes an observer function
  • empty: Clears the list array
  • fire: call fireWith
  • fireWith: Notifies the observer body of the received message.
  • lock: lock cbObj
  • disable: disable cbObj

The flow chart

Design tips for reference

$.Callbacks function clever parameter design

$.Callback takes both a string and a Js object. Strings such as “once memory” are parsed as {once:true,memory:true} objects, and the default arguments are treated as false.

This simplifies the entry process and works well for parameters that only need to be set to true or false.

Split the fire process

In the source code, instead of simply writing the fire implementation into a function, three methods are abstracted and the flow is clearer:

  1. Exposed fire methods. There is no need to set the function execution context (default iscbObjContext)
  2. The exposedfireWithMethods. You can set the observer function execution context
  3. The internal function that is actually responsible for executing and emptying the queuefire

1 and 2 are responsible for setting the execution context of the observer function and adding the message body to the queue. 3 Be responsible for message notification in specific execution queues.