Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 296
alexchenco Avatar asked Nov 18 '11 18:11

alexchenco


People also ask

What is on method in Nodejs?

The on() method requires name of the event to handle and callback function which is called when an event is raised. The emit() function raises the specified event. First parameter is name of the event as a string and then arguments. An event can be emitted with zero or more arguments.

What is on method in JavaScript?

Definition and Usage The on() method attaches one or more event handlers for the selected elements and child elements. As of jQuery version 1.7, the on() method is the new replacement for the bind(), live() and delegate() methods.

Is node js based on JavaScript?

NodeJS is a cross-platform and opensource Javascript runtime environment that allows the javascript to be run on the server-side. Nodejs allows Javascript code to run outside the browser. Nodejs comes with a lot of modules and mostly used in web development.

How do you call a method in node JS?

The call() method returns the result of calling the functionName() . By default, the this inside the function is set to the global object i.e., window in the web browsers and global in Node. js. Note that in the strict mode, the this inside the function is set to undefined instead of the global object.


2 Answers

It is a method from Node's EventEmitter class:

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

like image 109
hugomg Avatar answered Sep 20 '22 00:09

hugomg


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.

like image 31
Tesserex Avatar answered Sep 21 '22 00:09

Tesserex