$.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 < 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;
}
}