nodejs 事件驱动编程例子
相信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
相关推荐
lieyeleaves 2019-06-26
sssdssxss 2020-09-22
dailinqing 2020-07-18
Noseparte 2020-04-15
seekerhit 2020-01-24
范群松 2019-12-22
gd0 2019-11-04
frank0 2019-10-12
longdan0 2013-12-02
bangrenzhuce 2019-06-29
meleto 2013-07-11
xuesong 2019-06-28
堆码时刻 2012-04-24
静 2019-06-28
adeyi 2019-06-21
袅袅青烟散 2019-06-20
zhihuijiao 2019-04-15