@chenng/aop-js

Function Decorator。

Usage no npm install needed!

<script type="module">
  import chenngAopJs from 'https://cdn.skypack.dev/@chenng/aop-js';
</script>

README

aop-js

Function Decorator。

《JavaScript 设计模式与开发实践》中装饰者模式给出的例子。

使用

yarn add @chenng/aop-js
import '@chenng/aop-js';

例子

分离非业务代码

let showLogin = function() {
  console.log('打开登陆浮层');
}
let log = function() {
  console.log(`上报标签为:${this.getAttribute('tag')}`);
}
showLogin = showLogin.after(log); // 打开浮层上报数据
document.getElementById('button').onclick = showLogin;

动态改变函数参数

let ajax = function(type, url, params) {
  console.log(params);
}

ajax = ajax.before((type, url, params) => {
  params.Token = 'Token';
});

ajax('get', 'https://xxx.com/userinfo', {name: 'chenng'}); // {name: 'chenng', Token: 'Token'}

表单校验

const validata = function() {
  if (username.value === '') {
    alert('查询用户不能为空');
    return false;
  }
}

const formSubmit = function() {
  const param = {
    username: username.value
  }
  ajax('https://xxx.com/getUserInfo', param);
}

formSubmit = formSubmit.before(validata);