zoukankan      html  css  js  c++  java
  • Node.js之事件监听和发送

    演示事件的发送和监听

    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!!!
    
  • 相关阅读:
    第09组 Alpha冲刺 (2/6)
    第08组 Beta冲刺 (1/5)
    第08组 Alpha冲刺 总结
    第08组 Alpha冲刺 (6/6)
    第08组Alpha冲刺(5/6)
    第08组 Alpha冲刺 (4/6)
    第08组 Alpha冲刺 (3/6)
    第08组 Alpha冲刺 (2/6)
    第08组 Alpha冲刺 (1/6)
    第12组 Beta冲刺(2/5)
  • 原文地址:https://www.cnblogs.com/machao/p/7028823.html
Copyright © 2011-2022 走看看