![]() But that’s what makes events that interesting: you can register just as many functions as you want. This isn’t that interesting, could just have called that one function if we wanted the bell to ring. Calling the emit() method will execute all the functions that are registered with the on method. The real magic happens the line after that, when we emit our event. This doesn’t really do anything, it just registers our function. This is done by the eventEmitter.on() method and as first argument the event, as second argument the function to be added. We add our ringBell function to the function list of the doorOpen event. It simply prints ‘ring ring ring’ in our console. After then we place the ringBell function inside a variable so that it can be called that way. ![]() Then we create a new instance of the EventEmitter class (which we are going to extend later). Var eventEmitter = new events.EventEmitter() įirst we load the events module, which is part of the Node.js core. So the shop example: var events = require('events') It will act a bit like the observer pattern where our event acts like subject and all functions attached to the event are like observers. As event I will take the example that when a person enters a shop, a bell may ring to show his presence. While Node.js has some useful built-in events, like the request event, wouldn’t it be useful to be able to create our own events and be able to trigger them ourselves? That’s what I’m going to talk about in this article.įirst I will show you how normal events are emitted. Instead of reading all the files necessary with every request (like PHP), with Node you just start your server, initiate most of the variables, declare your functions and then just wait for an event to occur. One of the reasons for Node.js’ high speed is the fact that it is coded around events.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |