zoukankan      html  css  js  c++  java
  • Node.js自定义对象事件监听与发射

    一、Node.js是以事件驱动的,那我们自定义的一些js对象就需要能监听事件以及发射事件。在Node.js中事件使用一个EventEmitter对象发出,该对象在events模块中。它应该是使用观察者设计模式来实现把事件监听器添加到对象以及移除,之前写OC那块的时候也有些观察者设计模式,在OC中也经常用到:通知中心、KVO,也很容易理解.

    .addListener(eventName,callback):将回调函数附加到对象的监听器中。当eventName的事件被触发时,回调函数被放置在事件队列中执行。

    .on(eventName,callback):和.addListener一样。

    .once(eventName,callback),也是监听不过只在第一次被触发。

    .listeners(eventName):返回一个连接到eventName事件的监听器函数数组。

    .setMaxListeners(n):如果多于n的监听器加入到EventRmitter对象,就会出发警报.

    .removeListener(eventName,callback):将callback函数从EventEmitter对象的eventName事件中移除。

    二、上面写了那么多也都是EventEmitter对象方法的使用,自定义的对象怎么能使用它们才是关键!

    监听方法都是在EventEmitter对象,要想让自定义的对象也能使用这些方法,那就需要继承EventEmitter。

    js中实现继承有好几种方法:构造函数、原型链、call、apply等,可以百度一下:js继承。关于原型对象原型链这个写的挺不错:http://www.cnblogs.com/shuiyi/p/5305435.html

    只需将Events.EventEmitter.prototype添加到对象原型中.(在EventEmitter中是通过prototype来添加的监听器方法)

    三、使用

    var events = require('events');
    function Account() {
        this.balance = 0;
        //买的资料书上写要添加下面的语句,我将下面语句注释掉也能实现继承,应该是不需要的吧
        //events.EventEmitter.call(this);
        this.deposit = 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 overdrawn!!!");
        }
    }
    function checkGoal(acc, goal){
        if (acc.balance > goal){
            console.log("Goal Achieved!!!");
        }
    }
    var account = new Account();
    account.on("balanceChanged", displayBalance);
    account.on("balanceChanged", checkOverdraw);
    account.on("balanceChanged", function(){
        checkGoal(this, 1000);
    });
    account.deposit(220);
    account.deposit(320);
    account.deposit(600);
    account.withdraw(1200);
    Account balance: $220
    Account balance: $540
    Account balance: $1140
    Goal Achieved!!!
    Account balance: $-60
    Account overdrawn!!!
    
    Process finished with exit code 0
  • 相关阅读:
    大屏展示功能
    单例模式/原型模式
    .net core ioc
    Log4net
    mvc 过滤器
    webservice
    页面传值 作用域
    Map使用方法
    java获取当前时间撮
    linux 下统计文本行数的各种方法(一)
  • 原文地址:https://www.cnblogs.com/5ishare/p/5294552.html
Copyright © 2011-2022 走看看