Node.js之事件监听和发送
2017-06-16 18:21
453 查看
演示事件的发送和监听
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!!!
相关文章推荐
- Node.js EventEmitter 事件监听
- sails.js 使用node-cron模块,监听订单状态并发送消息到企业微信
- 【Node.js】mongoose教程02--开启、关闭数据库,监听数据库事件
- Node.js-事件模块(events)之监听方式
- node.js EventEmitter发送和接收事件
- 从零开始学习Node.js系列教程六:EventEmitter发送和接收事件的方法示例
- Node.js的事件监听函数代码
- 从零开始学习Node.js例子六 EventEmitter发送和接收事件
- Node.js自定义对象事件监听与发射
- Js监听事件
- Js 怎么自定义onResize事件监听
- 揭秘node.js事件
- 利用JavaScript开发事件驱动的Web应用 – node.js简介
- js 下拉框添加监听事件和js中删除一个对象
- JS 监听按钮单击事件
- Node.js的事件机制
- js 添加监听事件,包含jquery和DOM对象的转换
- java IP地址,端口校验+下拉菜单选框监听事件+模拟QQ发送按钮旁的小箭头功能
- JS中的事件监听操作
- 服务器端脚本node.js事件驱动