此 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:01:07  来源:igfitidea点击:

Is the 'on' method in this node.js code a JavaScript method or a node method?

javascriptnode.js

提问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 .onmethod(?). 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 .onon jQuery. Is it similar to the jQuery .liveevent handler?

有一种.on方法(?)。它能做什么?它是一个 JavaScript 方法吗?或者它是您只能在节点中找到的东西?我有点困惑,因为我想我.on在 jQuery 上看到了类似的东西。它是否类似于 jQuery.live事件处理程序?

Can anyone explain this to me?

任何人都可以向我解释这一点吗?

采纳答案by hugomg

回答by Tesserex

In this case, onis 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

For those looking for an easy explanation, it is node native implementation, and it's an alias of addListener(evtName, func) Check the API here

对于那些寻找简单解释的人,它是节点本地实现,它是 addListener(evtName, func) 的别名,请在此处查看API

回答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");