节点事件发射器示例

时间:2014-09-17 20:22:58

标签: javascript node.js events observer-pattern

我认为,在使用Node的EventEmitter时,我有一个相当简单的例子来做我认为可能是Observer模式的事情。也就是说,我仍然在使用Node获取我的海边。当我与另一位开发人员一起审核时 - 它看似正确,但似乎有些奇怪。

奇怪的部分是LightBulb对象如何监听LightSwitch对象。 AFAIK,代码有效,但我觉得我做错了。

/*jslint node: true */

'use strict';

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

var LightSwitch = function(state) {
    var self = this;
    self.state = typeof state !== 'undefined' ? state : 'off';
};

util.inherits(LightSwitch, events.EventEmitter);

LightSwitch.prototype.changeState = function() {
    var self = this;
    // FIXME use if else
    if (self.state == 'on') {
        self.state = 'off';
        self.emit('off');
    } else if (self.state == 'off') {
        self.state = 'on';
        self.emit('on');
    }
};

var LightBulb = function(LightSwitch) {
    var self = this;
    self.state = 'off';
    self.switch = LightSwitch;

    self.switch.on('on', function() {
        self.state = 'on';
    });

    self.switch.on('off', function() {
        self.state = 'off';
    });
};

LightBulb.prototype.currentState = function() {
    var self = this;
    console.log('The switch is ' + self.switch.state);
    console.log('The light bulb is ' + self.state);
    console.log('\n');
}

var hallwayLightSwitch = new LightSwitch();

var hallwayLightBulb = new LightBulb(hallwayLightSwitch);

// Default!
console.log('--------- EVERYTHING IS OFF --------------');
console.log('Switch is ' + hallwayLightBulb.switch.state);
console.log('Bulb is ' + hallwayLightBulb.state);
console.log('\n');

// Flick it!
console.log('------------ LIGHTS ON! ------------------');
hallwayLightSwitch.changeState();
hallwayLightBulb.currentState();

// Flick it - again!
console.log('------------ LIGHTS OFF! -----------------');
hallwayLightSwitch.changeState();
hallwayLightBulb.currentState();

// And, flick it - again!
console.log('------------ LIGHTS ON! -----------------');
hallwayLightSwitch.changeState();
hallwayLightBulb.currentState();

然后控制台输出......正如我所料:

[terryp@jinx] playing_with_events (master) :: node 02_lightswitch.js
--------- EVERYTHING IS OFF --------------
Switch is off
Bulb is off


------------ LIGHTS ON! ------------------
The switch is on
The light bulb is on


------------ LIGHTS OFF! -----------------
The switch is off
The light bulb is off


------------ LIGHTS ON! -----------------
The switch is on
The light bulb is on

0 个答案:

没有答案
相关问题