Giter Club home page Giter Club logo

events's Introduction

events Build Status

Node's event emitter for all engines.

This implements the Node.js events module for environments that do not have it, like browsers.

events currently matches the Node.js 11.13.0 API.

Note that the events module uses ES5 features. If you need to support very old browsers like IE8, use a shim like es5-shim. You need both the shim and the sham versions of es5-shim.

This module is maintained, but only by very few people. If you'd like to help, let us know in the Maintainer Needed issue!

Install

You usually do not have to install events yourself! If your code runs in Node.js, events is built in. If your code runs in the browser, bundlers like browserify or webpack also include the events module.

But if none of those apply, with npm do:

npm install events

Usage

var EventEmitter = require('events')

var ee = new EventEmitter()
ee.on('message', function (text) {
  console.log(text)
})
ee.emit('message', 'hello world')

API

See the Node.js EventEmitter docs. events currently matches the Node.js 11.13.0 API.

Contributing

PRs are very welcome! The main way to contribute to events is by porting features, bugfixes and tests from Node.js. Ideally, code contributions to this module are copy-pasted from Node.js and transpiled to ES5, rather than reimplemented from scratch. Matching the Node.js code as closely as possible makes maintenance simpler when new changes land in Node.js. This module intends to provide exactly the same API as Node.js, so features that are not available in the core events module will not be accepted. Feature requests should instead be directed at nodejs/node and will be added to this module once they are implemented in Node.js.

If there is a difference in behaviour between Node.js's events module and this module, please open an issue!

License

MIT

events's People

Contributors

birge avatar cedx avatar daffl avatar defunctzombie avatar denis-sokolov avatar friederbluemle avatar goto-bus-stop avatar gozala avatar jasonkarns avatar joseph-onsip avatar mattdesl avatar nolanlawson avatar qivhou avatar rudasn avatar shenanigans avatar zhangwinning avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

events's Issues

Support for engines without console?

Is there any desire to support engines without console?
I am currently writing code for a JavaScript engine bundled with Qt 4.8 that doesn't have it, so when I reached this line it crashed.

Therefore I replaced this module with this one for the time being however if there's inclination, I am happy to submit a PR.

how do I load this with vite/sveltekit?

I am trying to use the matrix-js-sdk package in sveltekit and it requires events (but need to run in the browser).

Is there a way I can import this module using vite (the svelte build tool) so that it exposes events api to browsers?

A better way to unset events?

I know there are methods to remove events, such as removeListener and removeAllListeners. But I think there should be a better method of removing events that don't correlate to the listener itself. Perhaps .on could return an object that keeps chainability, but also has special methods to kill that singular event.

let bar = foo.on(...);
bar.unset();
foo.on(...).on(...)

Please include a license

Hi there. It would be awesome from a distribution packaging point of view if you could include the full text of the MIT license in your software, usually in a file called LICENSE.

Thanks!

Question: why do not use events.forEach in emit() function?

Hi,

I have a question about best practices.

I'm trying to implement my own event emitter, and I was using the following code:

const length = listeners.length;
for (let i = 0, i < length; i++) {
    listeners[i].call(this, event);
}

But this throws an error if some listener removes itself because it'd change the array length while looping through the listeners.

So I decide to change to a forEach, something like:

listeners.forEach((listener) => listener.call(this, event));

And worked like a charm! But I did some research on some EventEmitter polyfills, and no one uses this pattern. Everyone uses an array clone pattern, and iterate with a for.

There's a specific reason to choose this pattern over another?

Thanks!

Error in handler should be thrown

ee.on('message', function (text) {
  console.log(gg) // gg is undefined
})

in the case above, it'should throw an error, but there is nothing

NPM@3 causes unwanted module overwrite

Before NPM version 3.0.0, I could use modules that require()'d this module, and then go ahead and use the Node core events module all I wanted. But now in NPM@3, the entire dependency tree is installed as flat as possible in the node_modules folder. This means that if I use a module that uses this module, I can no longer use the native events module anymore, because this one overwrites it. I did not put this module in my package.json as a dependency, an yet I am forced to use it. This should NOT be possible. If it's important to provide mirrors of the Node core modules in NPM, they should be under a different name. This wouldn't cause any problems, but it would solve this one.

Events.js has unhandled errors and errors regarding ports

events.js:292
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE: address already in use :::8081

My webserver can no longer start due to events.js throwing a fatal error that prevents me from listening on any ports. I am using Repl.it and events is used for Discord.js.

unhandled 'error' events should throw the error on next tick (setTimeout or setImmediate)

When EventEmitter.emit('error', error) is called in node, and goes unhandled, node will throw the error on the next tick, where it can't be handled by the current call stack.
This library throws the error during the emit call itself, which makes the error end up being thrown into a call stack that is not expecting it. This is particularly odd, because the caller is attempting to report the error, and it gets thrown back. I believe this behavior is incorrect.

I think the correct behavior, to mimic node, would be report the error using setTimeout or setImmediate, to clear the call stack before throwing. That way, the error will actually make it into the browser console output, which is generally benign.

??

Not covered by event built-in module of the node

Add preserved license comment

When this module is run through UglifyJS, the license comment is stripped. You can solve this by adding a comment like the following:

/*! events | Copyright Joyent, Inc. and other Node contributors | MIT License */

(At least some UglifyJS wrappers are configured to preserve comments beginning with a bang. A @license prefix may also work.)

Bower package?

Just want to see if there is a possibility to include bower support for frontend development.

When one listener throws an error, the next listeners are not called there is no error in Javascript console

This happened when on of my Store in my Flux application emit a 'CHANGE' event to its listeners.
Is there a good reason not to handle the exceptions here?

EventEmitter.prototype.emit = function(type) {
  var er, handler, len, args, i, listeners;

  if (!this._events)
    this._events = {};

  // If there is no 'error' event listener then throw.
  if (type === 'error') {
    if (!this._events.error ||
        (isObject(this._events.error) && !this._events.error.length)) {
      er = arguments[1];
      if (er instanceof Error) {
        throw er; // Unhandled 'error' event
      }
      throw TypeError('Uncaught, unspecified "error" event.');
    }
  }

  handler = this._events[type];

  if (isUndefined(handler))
    return false;

  if (isFunction(handler)) {
    switch (arguments.length) {
      // fast cases
      case 1:
        handler.call(this);
        break;
      case 2:
        handler.call(this, arguments[1]);
        break;
      case 3:
        handler.call(this, arguments[1], arguments[2]);
        break;
      // slower
      default:
        args = Array.prototype.slice.call(arguments, 1);
        handler.apply(this, args);
    }
  } else if (isObject(handler)) {
    args = Array.prototype.slice.call(arguments, 1);
    listeners = handler.slice();
    len = listeners.length;
    for (i = 0; i < len; i++)
      listeners[i].apply(this, args);
  }

  return true;
};

Wish: document in what cases this is needed

Node.js have a native events implementation, so it would be useful to note in the README in what cases there is a benefit or requirement to use this module over the native events module.

node v0.5.0-pre compatibility

npm ERR! Unsupported
npm ERR! Not compatible with your version of node/npm: [email protected]
npm ERR! Required: {"node":"0.4.x","teleport":">=0.2.0"}
npm ERR! Actual: {"npm":"1.0.10","node":"v0.5.0-pre"}
npm ERR!
npm ERR! System Linux 2.6.38-8-generic
npm ERR! command "node" "/usr/local/bin/npm" "install" "events"
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! /home/nb/npm-debug.log
npm not ok

Maintainer Needed

I personally don't have time to invest into this project, and I believe so does @defunctzombie
If you want to help maintaining this project please let us know.

Regards

Minimalist version

Minimalist version i coded for scratch coders like me lmao.

class Emitter {
    constructor() {
        this.eventsNames = {}
        
        this.on = (callName, callback_f) => {
            if(typeof callback_f != 'function') throw new Error("Callback must must type of 'function'.")
            if(this.eventsNames[callName] == undefined) this.eventsNames[callName] = []
            this.eventsNames[callName].push(callback_f)
        }
        this.emit = (callName, datas) => {
            if(this.eventsNames[callName] == undefined) return;
            for(let i in this.eventsNames[callName]) {
                try { this.eventsNames[callName][i](datas) } catch(e) { console.log(e) }
            }
        }
        this.removeListeners = (callName) => (this.eventsNames[callName] = [])
        this.removeAllListeners = (callName) => (this.eventsNames = {})
        this.countListeners = (callName) => (this.eventsNames[callName] != undefined ? this.eventsNames[callName].length : 0)
    }
}
let emitter = new Emitter()
emitter .on("hello", () => { console.log("hello world") })
emitter.emit("hello")

enderjs (browser) compatibility

With just a slight modification from the original Node source, this could be made browser compatible, will attach pull request.

TypeError: Cannot read property 'EventEmitter' of undefined typescript nodejs

I have a typescript application running on node.

I am using 'EventEmitter' class to emit a change in variable value.

This is my piece of code,

import events from 'events';

public async updateStream(streamContext: string, state: boolean): Promise<string> {
    const eventEmitter = new events.EventEmitter();
    if (state === true) {
      return StreamManagement.instance.activeStreams.get(streamContext).streamState = 'Paused';
    } else {
      const streamState = StreamManagement.instance.activeStreams.get(streamContext).streamState = 'Active';
      eventEmitter.emit('resume');
      return streamState;
    }
  }

 public async waitForStreamActive(stream: Stream) {
    const eventEmitter = new events.EventEmitter();
    // tslint:disable-next-line:no-unused-expression
    return new Promise(( resolve ) => {
      eventEmitter.on('resume', resolve );
    });
  }

This piece of code builds fine. But when i run the code, as in execute the operation, I am getting the following error,

error: errorHandler - Apply - Hit Unhandled exception {"timestamp":"2019-04-29T12:33:49.209Z"}
error: errorHandler - Apply - Cannot read property 'EventEmitter' of undefined - TypeError: Cannot read property 'EventEmitter' of undefined
    at StreamResource.updateStream (C:\Vertigo\core\reference_platform\dist\index.js:10695:51)
    at StreamService.patchStream (C:\Vertigo\core\reference_platform\dist\index.js:22524:40)
    at process._tickCallback (internal/process/next_tick.js:68:7) {"timestamp":"2019-04-29T12:33:49.215Z"}

What am I doing wrong?

Add events.once

Node.js 11.13 added an EventEmitter.once method: https://nodejs.org/api/events.html#events_events_once_emitter_name

It returns a Promise that resolves when the requested event is fired. If an 'error' event is fired first, the Promise rejects with the error.

The path to implementing this looks a bit like:

  • Finding the Node.js implementation (start in lib/events.js in the nodejs/node repository)
  • Finding the Node.js tests for this method. Test files are normally named something like test-modulename-functionname.js so you can find them by searching for events-once via the Github UI https://github.com/nodejs/node/find/master
  • Copy-paste the test file from Node.js into tests/ and add its require call to tests/index.js. Since this test will require Promise support, it should only be executed if Promises are available. See the require('./symbols.js') call for one approach. (We run browser tests in old IE etc, so Promise support isn't guaranteed.)
  • Copy-paste the implementation code into events.js at the correct location (it should be in the same order in the file as in Node.js, to make things easy to cross-reference).
  • Port everything to ES5…! It's okay for the method itself to fail if Promise doesn't exist. It should still be possible to use all other events features in environments that do not support Promises, though.
  • Document that Promise support or a global polyfill are required for the EventEmitter.once API to work in README.md.

We can then release this as a minor version.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.