What is an “event emitter”?

前端 未结 4 1494
情歌与酒
情歌与酒 2020-12-12 13:04

Browsing through http://microjs.com, I see lots of libraries labelled \"event emitters\". I like to think I know my way around the basics of the Javascript language pretty

4条回答
  •  长情又很酷
    2020-12-12 13:34

    It triggers an event to which anyone can listen. Different libraries offer different implementations and for different purposes, but the basic idea is to provide a framework for issuing events and subscribing to them.

    Example from jQuery:

    // Subscribe to event.
    $('#foo').bind('click', function() {
        alert("Click!");
    });
    
    // Emit event.
    $('#foo').trigger('click');
    

    However, with jQuery in order to emit an event you need to have a DOM object, and cannot emit events from an arbitrary object. This is where event-emitter becomes useful. Here's some pseudo-code to demo custom events (the exact same pattern as above):

    // Create custom object which "inherits" from emitter. Keyword "extend" is just a pseudo-code.
    var myCustomObject = {};
    extend(myCustomObject , EventEmitter);
    
    // Subscribe to event.
    myCustomObject.on("somethingHappened", function() { 
        alert("something happened!");
    });
    
    // Emit event.
    myCustomObject.emit("somethingHappened");
    

提交回复
热议问题