0
点赞
收藏
分享

微信扫一扫

jQuery AOP例子


JavaScript 基于对象事件的 AOP 实现 [url]http://www.ibm.com/developerworks/cn/web/1212_lincy_jsaop/[/url]
简洁优雅的JS AOP实现 [url]http://www.iteye.com/topic/68344[/url]
jQuery Aop 简明教程 [url]http://gty509.iteye.com/blog/379734[/url]
在jQuery中添加AOP的功能,可以使用jquery plugin.[url]http://code.google.com/p/jquery-aop/[/url]。使用非常简单,包含.js文件,然后调用添加通知的函数。
一共有四种通知:前置通知,后置通知,环绕通知和引入。

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

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

例:

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);   
  }  
);





后置通知:[b][color=darkblue]after[/color][/b] (Map pointcut, Function advice) return Array<Function>


通知(advice)在定义的切入点后面执行(pointcut),并接收切入点方法运行后的返回值作为参数




参数:


[b]pointcut: 织入点对象


target:被织入的对象


method:被织入的方法名字。


advice: 通知函数,并接受切入点方法执行后的返回值作为参数 [/b]



例:


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);   
  }  
);




环绕通知:[color=indigo][b]around[/b][/color] (Map pointcut, Function advice) return Array<Function>


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



参数:


[b]pointcut: 织入点对象


target:被织入的对象


method:被织入的方法名字。


advice: 通知函数,有一个参数innovation。包含.proceed()方法和两个属性:.argurments及.method [/b]



例:


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();   
  }  
);





引入:[color=darkblue][b]introduction[/b][/color] (Map pointcut, Function advice) return Array<Function>


此类型的通知的方法(advice)将替代制定切入点的方法。要恢复原方法,唯有卸载通知。


参数:


[b]pointcut: 织入点对象


target:被织入的对象


method:被织入的方法名字。


advice: 通知函数。[/b]



例:


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

举报

相关推荐

0 条评论