


Detailed explanation of the complete functional code of jQuery Callbacks by yourself_jquery
The usage is exactly the same as $.Callbacks, but it only implements add, remove, fire, empty, has and constructor functions with parameters. $.Callbacks also has disable, disabled, fireWith, fired, lock, locked methods
The code is as follows:
String.prototype.trim = function ()
{
return this.replace( /^\s+|\s+$/g, '' );
};
// Simulate jQuery.Callbacks object
function MyCallbacks( options )
{
var ops = { once: false, memory: false, unique: false, stopOnFalse: false };
if ( typeof options === 'string' && options.trim() !== '' )
{
var opsArray = options.split( /\s+/ );
for ( var i = 0; i {
if ( opsArray[i] === 'once' )
ops.once = true;
else if ( opsArray[i] === 'memory' )
ops.memory = true;
else if ( opsArray[i] === 'unique' )
ops.unique = true;
else if ( opsArray[i] === 'stopOnFalse' )
ops.stopOnFalse = true;
}
}
var ar = [];
var lastArgs = null;
var firedTimes = 0;
function hasName( name )
{
var h = false;
if ( typeof name === 'string'
&& name !== null
&& name.trim() !== ''
&& ar.length > 0 )
{
for ( var i = 0; i {
if ( ar[i].name === name )
{
h = true;
break;
}
}
}
return h;
}
// add a function
this.add = function ( fn )
{
if ( typeof fn === 'function' )
{
if ( ops.unique )
{
// check whether it had been added before
if ( fn.name !== '' && hasName( fn.name ) )
{
return this;
}
}
ar.push( fn );
if ( ops.memory )
{
// after added , call it immediately
fn.call( this, lastArgs );
}
}
return this;
};
// remove a function
this.remove = function ( fn )
{
if ( typeof ( fn ) === 'function'
&& fn.name !== ''
&& ar.length > 0 )
{
for ( var i = 0; i {
if ( ar[i].name === fn.name )
{
ar.splice( i, 1 );
}
}
}
return this;
};
// remove all functions
this.empty = function ()
{
ar.length = 0;
return this;
};
// check whether it includes a specific function
this.has = function ( fn )
{
var f = false;
if ( typeof ( fn ) === 'function'
&& fn.name !== ''
&& ar.length > 0 )
{
for ( var i = 0; i {
if ( ar[i].name === fn.name )
{
f = true;
break;
}
}
}
return f;
};
// invoke funtions it includes one by one
this.fire = function ( args )
{
if ( ops.once && firedTimes > 0 )
{
return this;
}
if ( ar.length > 0 )
{
var r;
for ( var i = 0; i {
r = ar[i].call( this, args );
if ( ops.stopOnFalse && r === false )
{
break;
}
}
}
firedTimes ;
if ( ops.memory )
{
lastArgs = args;
}
return this;
};
};
测试函数如下:(注意fn1 fn2是匿名函数, fn2返回false , fn3是有“名”函数)
var fn1 = function ( v )
{
console.log( 'fn1 ' ( v || '' ) );
};
var fn2 = function ( v )
{
console.log( 'fn2 ' ( v || '' ) );
return false;
};
function fn3( v )
{
console.log( 'fn3 ' ( v || '' ) );
};
1. Test add & fire
var cb=new MyCallbacks();
cb.add(fn1)
cb.add(fn2)
cb.add(fn3)
cb.fire('hello')
Output:
fn1 hello
fn2 hello
fn3 hello
2. Test remove
var cb=new MyCallbacks();
cb.add(fn1)
cb.add(fn2)
cb.add(fn3)
cb.remove(fn1)
cb.fire('hello')
cb.remove(fn3)
cb.fire('hello')
Output:
fn1 hello
fn2 hello
fn3 hello
----------------------------------
fn1 hello
fn2 hello
2. Test has
var cb=new MyCallbacks();
cb.add(fn1)
cb.add(fn2)
cb.add(fn3)
cb.has(fn1)
cb.has(fn3)
Output:
false
---------------
true
3. Test the constructor with parameters: once
var cb=new MyCallbacks('once')
cb.add(fn1)
cb.fire('hello')
cb.fire('hello')
cb.add(fn2)
cb.fire('hello')
Output:
hello
------------------
------------------
-----------------------------
4. Test the constructor with parameters: memory
var cb=new MyCallbacks('memory')
cb.add(fn1)
cb.fire('hello') // Output: fn1 hello
cb.add(fn2) // Output: fn2 hello
cb.fire('hello')
Output:
fn1 hello
fn2 hello
5. Test the constructor with parameters: stopOnFalse
var cb=new MyCallbacks('stopOnFalse')
cb.add(fn1)
cb.add(fn2)
cb.add(fn3)
cb.fire('hello')
Output:
fn1 hello
fn2 hello
6. Test the constructor with parameters: unique
var cb=new MyCallbacks('unique')
b.add(fn3)
b.add(fn3)
cb.fire('hello')
Output:
fn3 hello
7. Test the constructor with combined parameters: the four setting parameters can be combined at will. Only test all combinations at once, otherwise you will have to write 16 test cases T_T
var cb=new MyCallbacks('once memory unique stopOnFalse')
cb.add(fn1) // Output: fn1
cb.add(fn2) // Output: fn2
cb.add(fn3) // Output: fn3
cb.fire('hello')
Output:
fn1 hello
fn2 hello
cb.fire('hello') // Output: No output
The following is the official API document:
Description: A multi-purpose callbacks list object that provides a powerful way to manage callback lists.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.
Constructor: jQuery.Callbacks( flags )
flags
Type: String
An optional list of space-separated flags that change how the callback list behaves.
Possible flags:
once: Ensures the callback list can only be fired once ( like a Deferred).
memory: Keeps track of previous values and will call any callback added after the list has been fired right away with the latest "memorized" values (like a Deferred).
unique: Ensures a callback can only be added once (so there are no duplicates in the list).
stopOnFalse: Interrupts callings when a callback returns false.
By default a callback list will act like an event callback list and can be "fired" multiple times.
Two specific methods were being used above: .add() and .fire(). The .add() method supports adding new callbacks to the callback list, while the .fire() method executes the added functions and provides a way to pass arguments to be processed by the callbacks in the same list.
Use Callbacks to implement publish-subscribe mode pub/sub: (official document)
var topics = {};
jQuery.Topic = function ( id )
{
var callbacks,
method,
topic = id && topics[id];
if ( !topic )
{
callbacks = jQuery.Callbacks();
topic = {
publish: callbacks.fire,
subscribe: callbacks.add,
unsubscribe: callbacks.remove
};
if ( id )
{
topics[id] = topic;
}
}
return topic;
};
使用
$.Topic( 'mailArrived' ).subscribe( function ( e )
{
console.log( 'Your have new email! ' );
console.log( "mail title : " e.title );
console.log( "mail content : " e.content );
}
);
$.Topic( 'mailArrived' ).publish( { title: 'mail title', content: 'mail content' } );
实现了其余的全部功能 :callbacks.disable , callbacks.disabled, callbacks.fired,callbacks.fireWith, callbacks.lock, callbacks.locked ,然后重构了下代码结构, 将实现放入了匿名函数内, 然后通过工厂方法 window.callbacks 返回实例,以免每次使用必须 new .
具体代码如下, 有兴趣和时间的可以对照jQuery版本的Callbacks对比下 :
( function ( window, undefined )
{
// Simulate jQuery.Callbacks object
function Callbacks( options )
{
var ops = { once: false, memory: false, unique: false, stopOnFalse: false },
ar = [],
lastArgs = null,
firedTimes = 0,
_disabled = false,
_locked = false;
if ( typeof options === 'string' && options.trim() !== '' )
{
var opsArray = options.split( /\s+/ );
for ( var i = 0; i {
if ( opsArray[i] === 'once' )
ops.once = true;
else if ( opsArray[i] === 'memory' )
ops.memory = true;
else if ( opsArray[i] === 'unique' )
ops.unique = true;
else if ( opsArray[i] === 'stopOnFalse' )
ops.stopOnFalse = true;
}
}
function hasName( name )
{
var h = false;
if ( typeof name === 'string'
&& name !== null
&& name.trim() !== ''
&& ar.length > 0 )
{
for ( var i = 0; i {
if ( ar[i].name === name )
{
h = true;
break;
}
}
}
return h;
}
// add a function
this.add = function ( fn )
{
if ( typeof fn === 'function' )
{
if ( ops.unique )
{
// check whether it had been added before
if ( fn.name !== '' && hasName( fn.name ) )
{
return this;
}
}
ar.push( fn );
if ( ops.memory )
{
// after added , call it immediately
fn.call( this, lastArgs );
}
}
return this;
};
// remove a function
this.remove = function ( fn )
{
if ( typeof ( fn ) === 'function'
&& fn.name !== ''
&& ar.length > 0 )
{
for ( var i = 0; i {
if ( ar[i].name === fn.name )
{
ar.splice( i, 1 );
}
}
}
return this;
};
// remove all functions
this.empty = function ()
{
ar.length = 0;
return this;
};
// check whether it includes a specific function
this.has = function ( fn )
{
var f = false;
if ( typeof ( fn ) === 'function'
&& fn.name !== ''
&& ar.length > 0 )
{
for ( var i = 0; i {
if ( ar[i].name === fn.name )
{
f = true;
break;
}
}
}
return f;
};
this.disable = function ()
{
_disabled = true;
return this;
};
this.disabled = function ()
{
return _disabled;
};
this.fired = function ()
{
return firedTimes > 0;
};
function _fire( context, args )
{
if ( _disabled || ops.once && firedTimes > 0 || _locked )
{
return;
}
if ( ar.length > 0 )
{
var r;
for ( var i = 0; i {
r = ar[i].call( context, args );
if ( ops.stopOnFalse && r === false )
{
break;
}
}
}
firedTimes++;
if ( ops.memory )
{
lastArgs = args;
}
};
this.fireWith = function ( context, args )
{
context = context || this;
_fire( context, args );
return this;
};
this.fire = function ( args )
{
_fire( this, args );
return this;
};
this.lock = function ()
{
_locked = true;
return this;
};
this.locked = function ()
{
return _locked;
};
};
// exposed to global as a factory method
window.callbacks = function ( options )
{
return new Callbacks( options );
};
} )( window );

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.