while reading the node-mysql documantation i saw a usage as i pasted below
var query = connection.query('SELECT * FROM posts');
query
.on('error', function(err) {
// Handle error, an 'end' event will be emitted after this as well
})
.on('fields', function(fields) {
// the field packets for the rows to follow
})
.on('result', function(row) {
// Pausing the connnection is useful if your processing involves I/O
connection.pause();
processRow(row, function() {
connection.resume();
});
})
.on('end', function() {
// all rows have been received
});
i wonder how they use this events those can be used with the name whatever
user names the query query
in example when i create custom events i name them first for example var foo=new events.EventEmitter
and after this in whole page i have to use it as foo.on("someEvent")
but here they somehow bind the var created by user as event name in example code user names the mysql query as query
and the event emitter has the same name somehow
and second question how is that possible to chain events as they use
.on("event").on("anotherEvent")
this question may sound strange but i really wonder how this works and it will change my code design completely
query
is just your variable name for what is an instance of a Query
in the node-mysql lib. You get access to all the functions that object exports.
on
is inherited from EventEmitter
in the node.js core. The key thing is that calling on
returns "itself" i.e. this
:
Returns emitter, so calls can be chained.
This allows you to chain calls to on