此 node.js 代码中的“on”方法是 JavaScript 方法还是节点方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8187507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is the 'on' method in this node.js code a JavaScript method or a node method?
提问by alexchenco
I couldn't find this answer on Google because 'on' is such a common word. In this node.js example:
我在谷歌上找不到这个答案,因为“on”是一个很常见的词。在这个 node.js 示例中:
conn.on('close', function() {
var pos = connections.indexOf(conn);
if (pos >= 0) {
connections.splice(pos, 1);
}
});
There is a .on
method(?). What it does? It is a JavaScript method? Or it is something you only find in node? I'm kind of confused because I think I saw something like .on
on jQuery. Is it similar to the jQuery .live
event handler?
有一种.on
方法(?)。它能做什么?它是一个 JavaScript 方法吗?或者它是您只能在节点中找到的东西?我有点困惑,因为我想我.on
在 jQuery 上看到了类似的东西。它是否类似于 jQuery.live
事件处理程序?
Can anyone explain this to me?
任何人都可以向我解释这一点吗?
采纳答案by hugomg
It is a method from Node's EventEmitter class:
它是来自 Node 的 EventEmitter 类的一个方法:
https://nodejs.org/docs/latest/api/events.html#events_emitter_on_eventname_listener
https://nodejs.org/docs/latest/api/events.html#events_emitter_on_eventname_listener
回答by Tesserex
In this case, on
is a node method. jQuery also has a method of the same name, and they're used for basically the same purpose - binding event handlers to events by their string name. In fact the signatures look identical to me, IIRC.
在这种情况下,on
是一个节点方法。jQuery 也有一个同名的方法,它们的用途基本相同——通过字符串名称将事件处理程序绑定到事件。事实上,签名看起来与我相同,IIRC。
Pure JavaScript doesn't have such a method.
纯 JavaScript 没有这样的方法。
回答by Zaloz
回答by alessioalex
As you may know, Node.js is evented, thus listening for events (pub-sub), just like jQuery or Backbone for example.
您可能知道,Node.js 是事件化的,因此监听事件(发布-订阅),就像 jQuery 或 Backbone 一样。
In Node.js, you usually bind functions (using 'on' or other functions) to listen to events.
在 Node.js 中,您通常会绑定函数(使用 'on' 或其他函数)来监听事件。
From the Node.js documentation:
从 Node.js文档:
For example net.Server emits an event each time a peer connects to it, a fs.readStream emits an event when the file is opened. All objects which emit events are instances of events.EventEmitter. You can access this module by doing: require("events");
例如,net.Server 每次对等连接时都会发出一个事件,fs.readStream 在打开文件时会发出一个事件。所有发出事件的对象都是 events.EventEmitter 的实例。您可以通过以下方式访问此模块: require("events");