1. XenForo 1.5.14 中文版——支持中文搜索!现已发布!查看详情
  2. Xenforo 爱好者讨论群:215909318 XenForo专区

新闻 koahubjs 0.09 发布,新增钩子机制 下载

本帖由 漂亮的石头2016-10-11 发布。版面名称:软件资讯

  1. 漂亮的石头

    漂亮的石头 版主 管理成员

    注册:
    2012-02-10
    帖子:
    487,979
    赞:
    47
    koahubjs发布0.09 新增钩子机制


    添加钩子机制,控制器钩子和函数钩子
    修复自动加载bug,实现除自动加载导出的default外,还能自动加载其他的方法

    记koahubjs钩子开发过程


    在使用koahubjs开发项目完成之后,总是需要另外增加一些插件功能,这种情况下改动项目代码,风险太大,所以钩子机制不可缺少。koahubjs将钩子加载到了内存中,原因是因为koahubjs框架并没有内置数据库,而且加载到内存中更加灵活。

    钩子1

    控制器钩子


    执行某个http请求的时候,想要调用另外一个控制器的方法

    钩子2

    方法钩子


    执行某个http请求的时候,想要调用某个公共的函数

    直接上代码

    //创建hook.class.js
    // hooks 定义
    // {
    // addOrder: [
    // '/admin/index/index'
    // ]
    // }

    export default class {
    constructor() {
    this.hooks = {};
    }

    get() {
    return this.hooks;
    }

    add(name, action) {
    let add = true;
    for (let key in this.hooks) {
    if (name == key) {
    this.hooks[key].push(action);
    add = false;
    }
    }
    if (add) {
    this.hooks[name] = [action];
    }

    return this.get();
    }

    run(name) {
    for (let key in this.hooks) {
    if (name == key) {
    for (let path of this.hooks[key]) {
    if (/\w+\(.*\)$/.test(path)) {
    this.runFunction(path);
    } else {
    this.runController(path);
    }
    }
    }
    }
    }

    runController(path) {
    let action = path.slice(path.lastIndexOf('/'));
    path = path.slice(0, path.lastIndexOf('/'));

    let include = false;
    for (let _key in koahub.controllers) {
    if (_key == path) {
    include = true;
    break;
    }
    }

    if (include) {
    let ctrl = koahub.controllers[path];
    let pros = Object.getOwnPropertyNames(ctrl.prototype).filter(function(value) {
    if (value == 'constructor') {
    return false;
    }
    return true;
    });

    let callFlag = true;
    for (let k in pros) {
    if ('/' + pros[k] == action) {
    Object.getPrototypeOf(new ctrl())[pros[k]].call(this);
    callFlag = false;
    }
    }

    if (callFlag) {
    console.error('Hook Not Found Method');
    }
    } else {
    console.error('Hook Not Found Controller');
    }
    }

    runFunction(value) {
    eval(`koahub.utils.${value}`);
    }
    }

    钩子需要提前挂载到相应的节点上

    //开始挂载
    //controller钩子
    koahub.hook.add('hook1', '/admin/public/sendEmail');
    //function钩子
    koahub.hook.add('hook2', 'tools.add(1,2)');

    //调用钩子
    koahub.hook.run('hook1');
    koahub.hook.run('hook2');

    util方法

    //util下的*.util.js会自动挂载到koahub.utils上
    //util/tools.util.js
    export function add(a, b) {
    console.log(a + b);
    return a + b;
    }

    export function dis(a, b) {
    console.log(a - b);
    return a - b;
    }

    KoaHub.js – 基于 Koa.js 平台的 Node.js web 快速开发框架

    安装


    npm install koahubjs --save


    Star Github


    https://github.com/einsqing/koahubjs

    官网:http://js.koahub.com
    koahubjs 0.09 发布,新增钩子机制下载地址
     
正在加载...