12.How to Apply AOP
Overview
In hifive you can apply aspect to methods of logic and controller.
The advantage of AOP is that "you can add a new process without having to modify code".
For example, you can export the logs without having to modify existing methods. You can also measure the execution time for those methods as well.
How to apply aspect
Apply aspect to Hello World program created in Step 3.
1. Create a new h5preinit.js file and import prior to h5.js.
<script src="h5preinit.js"></script>
<script src="h5.js"></script>
2. The content of h5preinit.js is as below:
var aspect = {
target: 'HelloWorldController',
interceptors: h5.core.interceptor.lapInterceptor,
pointCut: '#btn click'
};
h5.settings.aspects = [aspect];
});
Aspect is defined by a hifive specific event (h5preinit).
It is described in details as below:
- Row 2 row 6 describe the definition of aspect. Aspect consists of target, pointcut and interceptor:
- Target defines which controller/logic interceptor is applied to. In this example, it is applied to a controller named "HelloWorldController".
- Interceptor is a process that needs to be executed. In this example, interceptor is defined to calculate the execution time of the built-in event handler and output to console.
- Pointcut defines where interceptor should be applied. In this example, interceptor is applied to "#btn click" method.
Checking operation
Press F12 to open Developer console, click "hello world!" button, execution time would be displayed to console.
If "h5preinit.js" is marked out as comments and not imported, result would not be displayed to console.
Reference
Next Chapter⇒ 13. Interacting with controllers