Why use event listeners over function calls?

前端 未结 5 1608
盖世英雄少女心
盖世英雄少女心 2021-01-17 12:02

I\'ve been studying event listeners lately and I think I\'ve finally gotten them down. Basically, they are functions that are called on another object\'s method. My questi

5条回答
  •  礼貌的吻别
    2021-01-17 12:21

    I think the main reason for events vs function calls is that events are 'listened to' while calls are 'made'. So a function call is always made to another object whereas listeners 'choose' to listen for an event to be broadcast from your object. The observer pattern is a good study for this capability. Here is a brief node.js example which illustrates the concept:

    var events = require('events');
    var Person = function(pname) {
        var name = pname;
    };
    
    
    var james = new Person('james');
    var mary = new Person('mary');
    var loudmouth = new Person('blabberer');
    
    loudmouth.mouth = new events.EventEmitter();
    
    //jame's observer.
    james.read_lips = function(msg){
        console.log("james found out: " + msg);
    };
    
    //james adds his event to the emitter's event listener.
    james.enter_elevator = function(){
        console.log('james is in the elevator');
        //NOTE: james adds HIMSELF as a listener for the events that may
        //transpire while he is in the elevator.
        loudmouth.mouth.on('elevator gossip', james.read_lips)
    };
    
    //james removes his event from the emitter when he leaves the elevator.
    james.leave_elevator = function(){
        // read lips is how james responds to the event.
        loudmouth.mouth.removeListener('elevator gossip', james.read_lips);
        console.log('james has left the elevator');
    };
    
    //mary's observer
    mary.overhear = function(msg){
        console.log("mary heard: " + msg);
    };
    
    //mary adds her observer event to the emitter's event listeners
    mary.enter_elevator = function(){
        // overhear is how mary responds to the event.
        console.log('mary is in the elevator');
        //NOTE: now mary adds HERSELF to the listeners in the elevator and 
        //she observes using a different method than james which suits her.
        loudmouth.mouth.on('elevator gossip', mary.overhear);
    };
    
    loudmouth.speaks = function(what_is_said){
        console.log('loudmouth: ' + what_is_said);
        this.mouth.emit('elevator gossip', what_is_said);
    };
    
    james.enter_elevator();
    mary.enter_elevator();
    loudmouth.speaks('boss is having an affair');
    james.leave_elevator();
    loudmouth.speaks('just kidding');
    console.log('james did not hear the last line because he was not listening anymore =)');
    

    so in this 'story' the actors choose to listen or when to not listen for events from a third party. I hope this helps.

提交回复
热议问题