当前位置: 首页 > 工具软件 > jQuery AOP > 使用案例 >

jQuery Aop 简明教程

夏侯俊美
2023-12-01
在jQuery中添加AOP的功能,可以使用jquery plugin.[url]http://code.google.com/p/jquery-aop/[/url]。使用非常简单,包含.js文件,然后调用添加通知的函数。
一共有四种通知:前置通知,后置通知,环绕通知和引入。

前置通知:before (Map pointcut, Function advice) return Array<Function>
在指定织入点创建一个前置通知。通知在被织入的方法之前执行,不能改变原方法的行为或阻止它执行。

参数:
pointcut: 织入点对象
target:被织入的对象
method:被织入的方法名字
advice: 通知函数

例:
jQuery.aop.before( {target: window, method: 'MyGlobalMethod'}, 
function() {
alert('About to execute MyGlobalMethod');
}
);

jQuery.aop.before( {target: window, method: /My/},
function() {
alert('About to execute one of my global methods');
}
);

jQuery.aop.before( {target: String, method: 'indexOf'},
function(index) {
alert('About to execute String.indexOf on: ' + this);
}
);


后置通知:after (Map pointcut, Function advice) return Array<Function>
通知(advice)在定义的切入点后面执行(pointcut),并接收切入点方法运行后的返回值作为参数


参数:
pointcut: 织入点对象
target:被织入的对象
method:被织入的方法名字。
advice: 通知函数,并接受切入点方法执行后的返回值作为参数

例:
jQuery.aop.after( {target: window, method: 'MyGlobalMethod'}, 
function(result) {
alert('Returned: ' + result);
}
);

jQuery.aop.after( {target: String, method: 'indexOf'},
function(index) {
alert('Result found at: ' + index + ' on:' + this);
}
);



环绕通知:around (Map pointcut, Function advice) return Array<Function>
在指定切入点处创建一个环绕通知,此类型的同志通过调用innovation.proceed()能够控制切入点方法的执行,也能在函数执行前更改它的参数。

参数:
pointcut: 织入点对象
target:被织入的对象
method:被织入的方法名字。
advice: 通知函数,有一个参数innovation。包含.proceed()方法和两个属性:.argurments及.method

例:
jQuery.aop.around( {target: window, method: 'MyGlobalMethod'}, 
function(invocation) {
alert('# of Arguments: ' + invocation.arguments.length);
return invocation.proceed();
}
);

jQuery.aop.around( {target: String, method: 'indexOf'},
function(invocation) {
alert('Searching: ' + invocation.arguments[0] + ' on: ' + this);
return invocation.proceed();
}
);

jQuery.aop.around( {target: window, method: /Get(\d+)/},
function(invocation) {
alert('Executing method ' + invocation.method);
return invocation.proceed();
}
);



引入:introduction (Map pointcut, Function advice) return Array<Function>
此类型的通知的方法(advice)将替代制定切入点的方法。要恢复原方法,唯有卸载通知。

pointcut: 织入点对象
target:被织入的对象
method:被织入的方法名字。
advice: 通知函数。

例:
jQuery.aop.introduction( {target: String, method: 'log'}, 
function() {
alert('Console: ' + this);
}
);
 类似资料: