美文网首页
Node.js之事件监听和发送

Node.js之事件监听和发送

作者: 老马的春天 | 来源:发表于2017-06-16 18:20 被阅读33次

演示事件的发送和监听

const events = require("events");

function Account() {
    this.balance = 0;
    events.EventEmitter.call(this);

    this.deposid = function (amount) {
        this.balance += amount;
        this.emit("balanceChanged");
    };

    this.withdraw = function (amount) {
        this.balance -= amount;
        this.emit("balanceChanged");
    };
}

Account.prototype.__proto__ = events.EventEmitter.prototype;

function displayBalance() {
    console.log("Account  balance: $%d", this.balance);
}

function checkOverdraw() {
    if (this.balance < 0) {
        console.log("Account overdraw!!!");
    }
}

function checkGoal(acc, goal) {
    if (acc.balance > goal) {
        console.log("Goal archieved!!!");
    }
}


const account = new  Account();
account.on("balanceChanged", displayBalance);
account.on("balanceChanged", checkOverdraw);
account.on("balanceChanged", function () {
    checkGoal(this, 1000);
});

account.deposid(220);
account.deposid(320);
account.deposid(620);
account.withdraw(1200);

打印结果:

Account  balance: $220
Account  balance: $540
Account  balance: $1160
Goal archieved!!!
Account  balance: $-40
Account overdraw!!!

相关文章

  • AS3:监听不到事件的原因之一

    前提:1、监听和事件发送代码都没有问题2、事件已经发送出去了3、监听却监听不到已经发送的事件示例代码:AS3 监听...

  • Node.js之事件监听和发送

    演示事件的发送和监听 打印结果:

  • Node.js - 事件 - events.EventEmitt

    Node.js EventEmitter Node.js 所有的异步 I/O 操作在完成时都会发送一个事件到事件...

  • signalR

    查看文档 创建连接 发送消息 监听事件 重连

  • 转载:nodejs 事件

    Node.js EventEmitter Node.js 所有的异步 I/O 操作在完成时都会发送一个事件到事件队...

  • Day4 Node.js EventEmitter

    Node.js EventEmitter Node.js 所有的异步 I/O 操作在完成时都会发送一个事件到事件队...

  • Node.js<二>

    Node.js EventEmitter Node.js 所有的异步 I/O 操作在完成时都会发送一个事件到事件队...

  • Node.js EventEmitter (触发器)

    Node.js EventEmitter Node.js 所有的异步 I/O 操作在完成时都会发送一个事件到事件队...

  • node.js(八)

    Node.js EventEmitter Node.js 所有的异步 I/O 操作在完成时都会发送一个事件到事件队...

  • Android耳机线控

    注册耳机事件监听器 其中关键语句是 当其他软件注册耳机监听事件后,系统就不会向该监听发送事件;解决方法:经测试,在...

网友评论

      本文标题:Node.js之事件监听和发送

      本文链接:https://www.haomeiwen.com/subject/nqpmqxtx.html