oo-eventtarget
v0.0.3
Published
Provides EventTarget interface to any object
Downloads
114
Readme
$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