hooker.js

来自「简单博客功能实现」· JavaScript 代码 · 共 65 行

JS
65
字号
/*
用于替代X2.Observer对象
提供函数钩子功能
能够获取被调用函数的参数
*/

/*
Hooker utility
based on prototype 1.4.1+
Using this utility, you can realize your custom event mechanism easily,
and you can build your web application quite extendable.
supNate@gmail.com
@2007-4-20
*/



X2.Hooker={
	//hooker can receive the arguments of the function which is hooked, and the arguments are following arguments passed by callback.
	hook:function(target,targetMethod,callback){
		var _targetMethod=target[targetMethod];
		if(!_targetMethod._hookers){
			var _oldMethod=_targetMethod;	//reserve the old method or function which is hooked
			target[targetMethod]=function(){
				_oldMethod.apply(target,arguments);
				var _args=arguments;
				arguments.callee._hookers.each(function(ob){
					if(ob)ob.apply(window,_args);
				});
			}
			Object.extend(target[targetMethod],_targetMethod);
			_targetMethod=target[targetMethod];
			_targetMethod._hookers=[];
		}
		_targetMethod._hookers.push(callback);
		return _targetMethod._hookers.length-1;
	}
	//delete a hooker
	,stopHook:function(targetMethod,i){
	    try{
		    targetMethod._hookers[i]=0;
		}catch(e){}
	}
	//clear all hookers
	,clearHookers:function(targetMethod){
	    try{
		    targetMethod._hookers.clear();
		}catch(e){}
	}
}

//act as a custom event mechanism
X2.Event={
    observe:function(target,eventName,callback){
        return X2.Hooker.hook.apply(X2.Hooker.hook,arguments);
    }
    ,stopObserve:function(dispatcher,i){
        X2.Hooker.stopHook(dispatcher,i);
    }
    ,clearObservers:function(dispatcher){
        X2.Hooker.clearHookers(dispatcher);
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?