我有一个回调类,我在 Js 类之间传递事件
var Callbacks = {};
Callbacks.triggers = {};
Callbacks.addCallback = function( trigger, instance, method ){
if( this.triggers[ trigger ] == undefined ){
this.triggers[ trigger ] = Array( { obj:instance, action:method } );
}else{
this.triggers[ trigger ].push( { obj:instance, action:method } );
};
};
Callbacks.fireCallback = function( trigger, param ){
if( this.triggers[ trigger ] == undefined ){
return;
};
for (var i=0; i < this.triggers[ trigger ].length; i++) {
var listener = this.triggers[ trigger ][ i ];
if( listener.action != undefined ){
listener.obj[ listener.action ]( param );
}
};
};
用法
/// some class to listen to a callback
function ListenClass(){
this.build = function(){
Callbacks.addCallback( 'myCallback', this, 'triggerMethod' );
}
this.triggerMethod = function( params ){
alert( params );
}
this.build();
}
/// some class firing a callback
function TriggerClass(){
this.fire = function(){
alert( 'fired' );
Callbacks.fireCallback( 'myCallback', { value:'hey there this is a callback'} );
}
}