nodejs 事件驱动编程例子

aihenaichadeyun 2012-06-14

相信nodejs会越来越成功

在学习Nodejs强大有两处:Event-driven,AsynchronousI/Ocallback.Nodejs服务器发的程序是单线程方式,这就要求其对于block类型的I/O要异步处理,而对于计算密集型的代码,也要进行对线程编程,这里简单的写个nodejsEvent-driven的小例子.

var events = require('events');
var util = require('util');

// The Thing That Emits Event
Eventer = function(){
	
  events.EventEmitter.call(this);
  
  this.kapow = function(){
    var data = "BATMAN";
    this.emit('blamo', data);
  },

  this.bam = function(){
     this.emit("boom");
  };
};

util.inherits(Eventer, events.EventEmitter);
// The thing that listens to, and handles, those events

Listener = function(){
  this.blamoHandler =  function(data){
    console.log("** blamo event handled");
    console.log(data);
  },
  this.boomHandler = function(data){
    console.log("** boom event handled");
  };

};

// The thing that drives the two.
var eventer = new Eventer();
var listener = new Listener(eventer);
eventer.on('blamo', listener.blamoHandler);
eventer.on('boom', listener.boomHandler);

eventer.kapow();
eventer.bam();

/*function add(a, b)
{
	console.log('a + b: ' + (a + b) );
}

function sub(a, b)
{
	console.log('a - b' + (a - b));
}

add.call(sub, 3, 1);
*/

//result: 4

/*function Class1() 
{ 
    this.name = "class1"; 

    this.showNam = function() 
    { 
        console.log(this.name); 
    }; 
} 

function Class2() 
{ 
    this.name = "class2"; 
} 

var c1 = new Class1(); 
var c2 = new Class2(); 

c1.showNam.call(c2); */

//result: class2

/*function Class1() 
{ 
    this.showTxt = function(txt) 
    { 
        console.log(txt); 
    }; 
} 

function Class2() 
{ 
    Class1.call(this); 
} 

var c2 = new Class2(); 

c2.showTxt("cc");*/

//result: cc.

输出结果:

**blamoeventhandled

BATMAN

**boomeventhandled

相关推荐