Passing Additional Parameters to Callbacks

Most callbacks have automatic parameters passed to them, such as an error or a result buffer. A common question when working with callbacks is how to pass additional parameters to them from the calling function. The way to do this is to implement the parameter in an anonymous function and then call the callback with parameters from the anonymous function.

The code in Listing 4.5 shows how to implement callback parameters. There are two sawCar event handlers. Note that the sawCar event only emits the make parameter. The first event handler, on line 16, implements the logCar(make) callback handler. To add a color for logColorCar(), an anonymous function is used in the event handler defined in lines 17–21. A randomly selected color is passed to the call logColorCar(make, color). Figure 4.8 shows the output from Listing 4.5.

Listing 4.5 callback_parameter.js: Creating an anonymous function to add additional parameters that are not emitted by the event


01 var events = require('events'),
02 function CarShow() {
03   events.EventEmitter.call(this);
04   this.seeCar = function(make){
05     this.emit('sawCar', make);
06   };
07 }
08 CarShow.prototype.__proto__ = events.EventEmitter.prototype;
09 var show = new CarShow();
10 function logCar(make){
11   console.log("Saw a " + make);
12 }
13 function logColorCar(make, color){
14   console.log("Saw a %s %s", color, make);
15 }
16 show.on("sawCar", logCar);
17 show.on("sawCar", function(make){
18   var colors = ['red', 'blue', 'black'];
19   var color = colors[Math.floor(Math.random()*3)];
20   logColorCar(make, color);
21 });
22 show.seeCar("Ferrari");
23 show.seeCar("Porsche");
24 show.seeCar("Bugatti");
25 show.seeCar("Lamborghini");
26 show.seeCar("Aston Martin");


Image

Figure 4.8 Output of callback_parameter.js, showing the results of adding a color parameter to the callback.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.189.250