首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

nodejs 事件驱动编程例证

2012-08-27 
nodejs 事件驱动编程例子相信nodejs会越来越成功在学习Nodejs强大有两处: Event-driven, Asynchronous I/O

nodejs 事件驱动编程例子
相信nodejs会越来越成功

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

var events = require('events');var util = require('util');// The Thing That Emits EventEventer = 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 eventsListener = 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.



输出结果:

** blamo event handled
BATMAN
** boom event handled



热点排行