自己動(dòng)手實(shí)現(xiàn)jQuery Callbacks完整功能代碼詳解
用法和$.Callbacks完全一致 , 但是只是實(shí)現(xiàn)了add , remove , fire , empty, has和帶參數(shù)的構(gòu)造函數(shù)功能, $.Callbacks 還有disable,disabled, fireWith , fired , lock, locked 方法
代碼如下:
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 < options.length; 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 < ar.length; 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 < ar.length; 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 < ar.length; 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 < ar.length; i++ )
{
r = ar[i].call( this, args );
if ( ops.stopOnFalse && r === false )
{
break;
}
}
}
firedTimes++;
if ( ops.memory )
{
lastArgs = args;
}
return this;
};
};
測(cè)試函數(shù)如下:(注意fn1 fn2是匿名函數(shù), fn2返回false , fn3是有“名”函數(shù))
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 . 測(cè)試add & fire
var cb=new MyCallbacks();
cb.add(fn1)
cb.add(fn2)
cb.add(fn3)
cb.fire('hello')
輸出:
fn1 hello
fn2 hello
fn3 hello
2.測(cè)試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')
輸出:
fn1 hello
fn2 hello
fn3 hello
----------------------------
fn1 hello
fn2 hello
2.測(cè)試has
var cb=new MyCallbacks();
cb.add(fn1)
cb.add(fn2)
cb.add(fn3)
cb.has(fn1)
cb.has(fn3)
輸出:
false
---------------
true
3.測(cè)試帶參數(shù)的構(gòu)造函數(shù) : once
var cb=new MyCallbacks('once')
cb.add(fn1)
cb.fire('hello')
cb.fire('hello')
cb.add(fn2)
cb.fire('hello')
輸出:
hello
-------------------
------------------
------------------------------
4.測(cè)試帶參數(shù)的構(gòu)造函數(shù) : memory
var cb=new MyCallbacks('memory')
cb.add(fn1)
cb.fire('hello') // 輸出 : fn1 hello
cb.add(fn2) // 輸出 : fn2 hello
cb.fire('hello')
輸出 :
fn1 hello
fn2 hello
5.測(cè)試帶參數(shù)的構(gòu)造函數(shù) : stopOnFalse
var cb=new MyCallbacks('stopOnFalse')
cb.add(fn1)
cb.add(fn2)
cb.add(fn3)
cb.fire('hello')
輸出:
fn1 hello
fn2 hello
6.測(cè)試帶參數(shù)的構(gòu)造函數(shù) :unique
var cb=new MyCallbacks('unique')
b.add(fn3)
b.add(fn3)
cb.fire('hello')
輸出:
fn3 hello
7. 測(cè)試帶組合參數(shù)的構(gòu)造函數(shù):四個(gè)設(shè)置參數(shù)可以隨意組合,一下只測(cè)試全部組合的情況, 不然要寫(xiě)16個(gè)測(cè)試用例 T_T
var cb=new MyCallbacks('once memory unique stopOnFalse')
cb.add(fn1) // 輸出: fn1
cb.add(fn2) // 輸出: fn2
cb.add(fn3) // 輸出: fn3
cb.fire('hello')
輸出:
fn1 hello
fn2 hello
cb.fire('hello') // 輸出:沒(méi)有輸出
以下是官方API 文檔:
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.
構(gòu)造函數(shù) : 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.
利用Callbacks 實(shí)現(xiàn)發(fā)布訂閱模式 pub/sub: (官方文檔)
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' } );
實(shí)現(xiàn)了其余的全部功能 :callbacks.disable , callbacks.disabled, callbacks.fired,callbacks.fireWith, callbacks.lock, callbacks.locked ,然后重構(gòu)了下代碼結(jié)構(gòu), 將實(shí)現(xiàn)放入了匿名函數(shù)內(nèi), 然后通過(guò)工廠方法 window.callbacks 返回實(shí)例,以免每次使用必須 new .
具體代碼如下, 有興趣和時(shí)間的可以對(duì)照jQuery版本的Callbacks對(duì)比下 :
( 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 < options.length; 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 < ar.length; 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 < ar.length; 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 < ar.length; 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 < ar.length; 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 );
- jQuery源碼分析之Callbacks詳解
- jQuery.Callbacks()回調(diào)函數(shù)隊(duì)列用法詳解
- jQuery回調(diào)函數(shù)的定義及用法實(shí)例
- 使用jQuery中的when實(shí)現(xiàn)多個(gè)AJAX請(qǐng)求對(duì)應(yīng)單個(gè)回調(diào)的例子分享
- jQuery Tips 為AJAX回調(diào)函數(shù)傳遞額外參數(shù)的方法
- Jquery版本導(dǎo)致Ajax不執(zhí)行success回調(diào)函數(shù)
- jQuery AJAX回調(diào)函數(shù)this指向問(wèn)題
- Jquery Post處理后不進(jìn)入回調(diào)的原因及解決方法
- 從零學(xué)jquery之如何使用回調(diào)函數(shù)
- jquery.Callbacks的實(shí)現(xiàn)詳解
相關(guān)文章
jQuery代碼實(shí)現(xiàn)實(shí)時(shí)獲取時(shí)間
這篇文章主要介紹了jQuery代碼實(shí)現(xiàn)實(shí)時(shí)獲取時(shí)間功能,代碼簡(jiǎn)單易懂,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友參考下吧2017-01-01
jquery checkbox實(shí)現(xiàn)單選小例
checkbox是復(fù)選框如何將其變?yōu)閱芜x呢?下面有個(gè)不錯(cuò)的示例,感興趣的朋友可以參考下2013-11-11
asp.net+jquery.form實(shí)現(xiàn)圖片異步上傳的方法(附j(luò)query.form.js下載)
這篇文章主要介紹了asp.net+jquery.form實(shí)現(xiàn)圖片異步上傳的方法,結(jié)合實(shí)例形式分析了jquery.form.js前臺(tái)異步提交圖片與asp.net后臺(tái)處理的相關(guān)技巧,需要的朋友可以參考下2016-05-05
用Jquery實(shí)現(xiàn)可編輯表格并用AJAX提交到服務(wù)器修改數(shù)據(jù)
使用Jquery實(shí)現(xiàn)可編輯的表格 并使用AJAX提交到服務(wù)器修改數(shù)據(jù)的實(shí)現(xiàn)代碼。2009-12-12
jQuery實(shí)現(xiàn)頁(yè)面滾動(dòng)時(shí)動(dòng)態(tài)加載內(nèi)容的方法
這篇文章主要介紹了jQuery實(shí)現(xiàn)頁(yè)面滾動(dòng)時(shí)動(dòng)態(tài)加載內(nèi)容的方法,實(shí)例分析了jQuery實(shí)現(xiàn)動(dòng)態(tài)加載頁(yè)面的技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-03-03
精心挑選的15款優(yōu)秀jQuery 本特效插件和教程
今天這篇文章向大家分享15款精心挑選的優(yōu)秀 jQuery 文本特效插件,都帶有詳細(xì)的使用教程。jQuery 是最流行和使用最廣泛的 JavaScript 框架,它簡(jiǎn)化了 HTML 文檔遍歷,事件處理,動(dòng)畫(huà)以及Ajax交互,幫助 Web 開(kāi)發(fā)人員更快速的實(shí)現(xiàn)各種精美的界面效果2012-08-08
jQuery源碼分析-03構(gòu)造jQuery對(duì)象-工具函數(shù)
jQuery源碼分析-03構(gòu)造jQuery對(duì)象-工具函數(shù),需要的朋友可以參考下。2011-11-11

