Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including oo-eventtarget with all npm packages installed. Try it out:

var ooEventtarget = require("oo-eventtarget")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

oo-eventtarget v0.0.3

Provides EventTarget interface to any object

$EventTarget.js

$EventTarget.js is a mixin to provide event target functionality to any object.

When $EVentTarget is used on an object, all methods are added to the object's prototype.

Install

npm install oo-eventtarget

Usage

var $EventTarget = require("oo-eventtarget");
    
var Product = function(name, price) {
    $EventTarget(this); // add mixin to the product
    
    this.name = name;
    this.price = price;
};
    
Product.prototype.buy = function(quantity) {
    // dispatch a "buy" event
    this.dispatchEvent("buy", { quantity: quantity });
};

// listen to a product
var product = new Product("Millenium Falcon", 120);
product.addEventListener("buy", function(event) {
    console.log(event.type, event.data.quantity, event.target.name + "s");
});
product.buy(2); // logs "buy 2 Millenium Falcons"

Interface

$EventTarget#addEventListener(name, callback)

Adds a new listener to an object

  • name: the name of the event
  • callback(event): the function to call when the event is triggered.

$EventTarget#removeEventListener(name, callback)

Removes a listener from an object

  • name: the name of the event
  • callback(event): the function to remove

$EventTarget#dispatchEvent(name, data)

  • name: the name of the event to dispatch
  • data: the data to pass to the event (optional)

Event

  • type: the type of the event
  • target: the object that dispatched the event
  • data: the data passed with the event
RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free