【问题标题】:Code efficiency in Node.js for multiple events listenersNode.js 中多个事件侦听器的代码效率
【发布时间】:2015-08-16 04:50:57
【问题描述】:

我有一个代码可以在同一个 .js 文件中发出和处理事件。例如,发射事件的类型可以是“hello”、“world”、“user”等。所有事件处理函数(.on)都有类似的方法来处理错误和回调的核心函数内部的事件(完全相同)。有没有重构和改进冗余代码的建议。

localEvents.on("hello", function(request , reply){
    console.log("inside event for hello");
    hello.intialize() {
       // handle initialise error and callback //
    };
});

localEvents.on("world", function(request , reply){
    console.log("inside event for world");
    world.initialise() {
       // handle initialise error and callback //
    };
});

localEvents.on("user", function(request , reply){
    console.log("inside event for user");
    user.initialise() {
       // handle initialise error and callback //
    };
});

localEvents.emit(task, request, reply);

【问题讨论】:

  • 你能告诉我函数参数中的“请求”和“回复”是什么吗?
  • request 和 reply 是 hapi 服务器对象,如 express 中的 req 和 rep。

标签: javascript node.js dom-events hapijs eventemitter


【解决方案1】:

您可以创建一个辅助函数,例如:

function addHandler(evName, obj) {
  localEvents.on(evName, function(request, reply) {
    console.log("inside event for %s", evName);
    obj.initialise(function(err) {
       // handle initialise error and callback
    });
  });
}

然后就这样称呼它:

addHandler('hello', hello);
addHandler('world', world);
addHandler('user', user);

或者如果你真的想减少参数中的重复,你可以创建一个帮助器,比如:

function addHandler(evName) {
  var obj = eval(evName);
  localEvents.on(evName, function(request, reply) {
    console.log("inside event for %s", evName);
    obj.initialise(function(err) {
       // handle initialise error and callback
    });
  });
}

然后让你简单地做:

addHandler('hello');
addHandler('world');
addHandler('user');

【讨论】:

  • 我们将如何在上述方法中发出事件localEvents.emit(task, request, reply);
  • @user3601166 - .emit() 与以前完全相同。你的localEvents 变量没有改变,所以你就像以前一样localEvents.emit(...)
  • @jfriend00 - 明白。
【解决方案2】:

这样做的简单方法 - 这种方式对于您可能需要在事件回调函数中进行的任何更改都会更加灵活

var eventsList = {
    "hello": function(request, reply) {
        console.log("inside event for hello");
        hello.initialise() {
            // handle initialise error and callback //
        };
    },
    "world": function(request, reply) {
        console.log("inside event for world");
        world.initialise() {
            // handle initialise error and callback //
        };
    },
    "user": function(request, reply) {
        console.log("inside event for user");
        user.initialise() {
            // handle initialise error and callback //
        };
    }
}

function generateEvents(events){
    for(var e in events){
        localEvents.on(e, events.e)
    }
}

generateEvents(eventsList)

【讨论】:

  • 我们如何在这里发出事件?
  • 虽然这是一种组织代码的不同方式,但它并没有真正消除很多复制/重复的代码,所以我不确定这如何真正提高我认为 OP 的代码效率要求。
  • 事件发出的方式仍然与您相同
  • @jfriend00 是的,你是对的,但在现实世界中,代码不会像这里描述的那么简单。你总是不得不在至少一些灵活性和代码的重复性上做出妥协,因为它们都是成反比
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多