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

I couldn't find this answer on Google because 'on' is such a common word. In this node.js example:

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?

Can anyone explain this to me?

Answers


It is a method from Node's EventEmitter class:

https://nodejs.org/docs/latest/api/events.html#events_emitter_on_eventname_listener


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.

Pure JavaScript doesn't have such a method.


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


As you may know, Node.js is evented, thus listening for events (pub-sub), just like jQuery or Backbone for example.

In Node.js, you usually bind functions (using 'on' or other functions) to listen to events.

From the Node.js documentation:

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


Need Your Help

how can I get intellisense in a T4 template?

visual-studio visual-studio-2008 intellisense t4

When trying out these tutorials (T4 Tutorial: Creating reusable code generation templates) I noticed that although I was using plain c# I didn't get any intellisense, probably because of the file

Laravel: PDOException: could not find driver

php mysql apache laravel sqlite

I am developing a website on a server I only have access to MySQL and FTP, so all commands I run are through the b374k php shell . I am experiencing a Laravel problem with SQL driver. I tried switc...