Node.js 之向回调函数传递额外的参数

//emitter_listener.js:创建一个自定义 EventEmitter 对象并实现 balanceChanged 事件被触发时所触发的 3 个监听器
//从外部引入 events 模块包
var events = require("events");
//构造函数,定义方法来触发自定义事件
function CarShow(){
    events.EventEmitter.call(this);
    this.seeCar = function(make){
        this.emit('sawCar',make);
    };
}

CarShow.prototype.__proto__ = events.EventEmitter.prototype;
var show = new CarShow();

//两个回调方法 logCar,讲述看到了什么车,logColorCar 讲述看到什么颜色的什么车
function logCar(make){
    console.log("Saw a " + make);
}

function logColorCar(make,color){
    console.log("Saw a %s %s",color,make);
}

//给 show 对象的 sawCar 事件添加回调函数,参数的引入已经在构造函数定义的时候决定了
show.on("sawCar",logCar);
show.on("sawCar",function(make){
    var colors = ['red','blue','black'];
    var color = colors[Math.floor(Math.random()*3)];
    logColorCar(make,color);
});

show.seeCar("Ferrari");
show.seeCar("Prosche");
show.seeCar("Bugatti");
show.seeCar("Lamborghini");
show.seeCar("Aston Martin");

//给回调函数添加参数的话,需要在回调函数外部再套一层函数,通过这个函数来获取外部参数
  

执行结果:

Saw a Ferrari
Saw a red Ferrari
Saw a Prosche
Saw a red Prosche
Saw a Bugatti
Saw a red Bugatti
Saw a Lamborghini
Saw a red Lamborghini
Saw a Aston Martin
Saw a black Aston Martin
  

再来一发:

//场景:战斗中,战士看到敌人,首先隐蔽,然后向敌人开火,开火的时候,使用的武器随机
var events = require("events");
function Soldier(){
    events.EventEmitter.call(this);
    this.seeEnemy = function(weapon){
        this.emit("fight",weapon);
    }
}

Soldier.prototype.__proto__ = events.EventEmitter.prototype;

//回调函数
function hide(){
    console.log("Hide into the jungle");
}

function fire(weapon){
    console.log("Fire with %s",weapon);
}

var soldierBoy = new Soldier();
soldierBoy.on("fight",hide);
soldierBoy.on("fight",function(weapon){
    fire(weapon);
});

soldierBoy.seeEnemy("AK47");
soldierBoy.seeEnemy("G36");
soldierBoy.seeEnemy("M4A1");
  

执行结果:

Hide into the jungle
Fire with AK47
Hide into the jungle
Fire with G36
Hide into the jungle
Fire with M4A1