• Stars
    star
    12
  • Rank 1,593,149 (Top 32 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 10 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A same behaviour EventTarget prototype, that can work with any object from JavaScript

ObjectEventTarget

Gitter

npm version Build Status Dependency Status Coverage Status Code Climate

A same behaviour EventTarget prototype, that can work with any object from JavaScript

Motivation

You know as everybody knows how to use the EventTarget today, because every Node instance (HTML Elements) prototype it. And that's make it awesome. You can prototype your objects with this and you will have support to events.

Also it can be used as prototype of a shim to EventTarget in non-modern browsers. Because it's compatible with ES3.

Installation

To use in your browser, you just need to add the script before the place you are using it.

<script src="ObjectEventTarget.js"></script>

To install on NodeJS:

npm install objecteventtarget --save

Projects using it

  • Chronometer.js This is just a chronometer constructor in JavaScript, that uses ObjectEventTarget as prototype to support events listeners, demo page.
  • Entity This is a JavaScript micro lib that allows you to create entity with events of attribute manipulation.

How to use

Prototype your constructor like this:

function Foo(){}
Foo.prototype = ObjectEventTarget.prototype;

Now you have access to EventTarget methods, so let's implement a mehtod that dispatch a event type:

function AsyncFoo(){
  this.bar = function(){
    if (this.dispatchEvent({type: 'beforebar'})){
      console.log('The beforebar default behaviour');
    }
    // Do something then...
    var self = this;
    setTimeout(function (){
      // I'm async
      if (self.dispatchEvent(new ObjectEvent('bar', {cacelable: true})){
        console.log('The bar default behaviour');
      };
      console.log('End of bar method');
    }, 1e3);
  }
}
AsyncFoo.prototype = ObjectEventTarget.prototype;

Now you can add some events to you AsyncFoo instances like this:

instanceOne = new AsyncFoo();
instanceOne.addEventListener('beforebar', function (){
  console.log('You triggered bar from a AsyncFoo instance');
});
instanceOne.addEventListener('bar', function (event){
  event.preventDefault();
  console.log('The method bar was async and finished calling "bar" event type');
});
instanceOne.bar();
// #1: You triggered bar from a AsyncFoo instance
// #2: The beforebar default behaviour
// after a seccond
// #3: The method bar was async and finished calling "bar" event type
// #4: End of bar method

The rest you know...

Using with NodeJS

After installing on NodeJS you can use require('objecteventtarget') to get a object with ObjectEventTarget and ObjectEvent.

Example:

var ObjectEventTarget = require('objecteventtarget').ObjectEventTarget;
var ObjectEvent = require('objecteventtarget').ObjectEvent;

/* ... your code implemetation ... */

Methods

The methods aren't enumerables, but only for modern-browsers and nodejs, if you are supporting IE9- if you use for in in your object, make sure to check the hasOwnProperty, because if not, you will touch the methods.

  • addEventListener( eventType, callback )
  • removeEventListener( eventType, callback )
  • dispatchEvent( event ) The event can be any object that has "type" propertie as string, recomends to use new ObjectEvent('type name').

Events

You can use new ObjectEvent('type name', options) to generate a event compatible with non-modern browsers and Nodejs.

Or you can just use a literal object with at least type property aka {type: 'type name'}.

I don't encorage you to use the browser Event, but it will work with it events like Event, CustomEvent and anyone that prototypes Event, also you can use modern constructor or non-moderns, it will work where the browser supports it, but when using this way, it will never change the path property.

There is properties in a event that after start the type dispatch callback queue, becomes read-only properties, you should not try to force change their values.

  • type string (read) the name/type of the event
  • immediatePropagationStopped boolean (read/write) when a callback stoped the event chain (recomend to use the Event or CustomEvent constructor to use this)
  • cancelable boolean (read) define if the event can be cancelable when preventDefault is triggered
  • defaultPrevented boolean (read/write) when true will set the returnValue to be false if the event is cancelable
  • returnValue boolean (read) same value that is returned by the dispatchEvent method
  • eventPhase number (read) expose the phase where the event is been triggered
  • path array (read) a array with the objects in the orther that the event has triggered in it phases

Events Methods

When not available, because you probably used a literal object in the dispatchEvent, the event methods will be added to your object by mixing the methods in it.

  • initEvent() executed before the first callback in the queue be called, also keeps the integrity of your object with every required property and method been setup
  • preventDefault() will set defaultPrevented true when cancelable is true
  • stopImmediatePropagation() will stop the immidiate propagation of the callbacks of the event type in the current queue

Events Error Handling

When a callback from a event type throw an error, it will result in same as stopImmediatePropagation.

The throw will be show in your console, but will not stop your code flow that is expecting by the dispatchEvent result.

Projects Using it

Overloading internals

The ObjectEventTarget let you to overload it internal constructors to you personalize how it should work in your enviroment.

  • EventsMap( type, callback ) is created to store the events and callbacks, where type must become a property where contains a array of callbacks. If the instance exists it will decorate with new types with array and it callbacks.
  • WeakMap is used to map the instances to it EventsMap, and must contain the methods get( object ), set( object, value ), has( object ), delete( object ).

To do the overloading, before the lib is loaded you must create a object called ObjectEventTarget with the property options.

window.ObjectEventTarget = {
  options: {
    EventsMap: MyCustomEventsMap,
    WeakMap: MyCustomWeakMap
  }
};

More Repositories

1

pushStateTree

The most powerful JavaScript router library for Single Page Applications.
JavaScript
12
star
2

RequireJS-Wrapper-Plugin

A plugin to RequireJS where fix require files that doesn't support AMD pattern like: Backbone, Underscore, Zepto, jQuery, and any other that register a single global var
JavaScript
11
star
3

draughtsjs

A Draughts (Checkers / Damas) game in pure Javascript
JavaScript
10
star
4

node-bind-std-to-console

Run node with --inspect and see what is in your stdout and stderr. Simple like first import in your app boot.
JavaScript
9
star
5

chronometer.js

This is just a chronometer constructor in JavaScript, that uses ObjectEventTarget as prototype to support events listeners.
JavaScript
8
star
6

FirePHP-TextMate-Bundle

A TextMate Bundle for using with FirePHP
8
star
7

html

A RequireJS/AMD loader plugin for loading html fragments from plain text html files.
JavaScript
6
star
8

Entity

A Javascript entity with support a events and export toJSON very simple that can be extended using prototype chain.
JavaScript
5
star
9

requirejs-link

RequireJS plugin to insert LINK element on DOM, work with CSS and HTMLImport
JavaScript
5
star
10

snake-js

Boring afternoon snake game.
JavaScript
4
star
11

chrome-fbvideo

Facebook Lost Video Chrome Plugin
JavaScript
3
star
12

yo-letmein

A home project to be used with Raspberry PI, that starts a server to allow YO trigger the GPIO to do stuffs like open doors
JavaScript
3
star
13

RapidLeetch

Rapid Leech is a free server transfer script for use on various popular upload/download sites such as megaupload.com, Rapidshare.com and more than 45 others. The famous Rapidleech script transfers files from Rapidshare, Megaupload, Depositfiles.com, Easy-share.com, etc, via your fast servers connection speed and dumps the file on your server. You may then download these files from your server anytime later.
PHP
3
star
14

G-Lock-Double-Opt-in-Manager--Wordpress-Plugin-

This mailing list management plugin allows the visitors of your blog subscribe to your mailing list using a double opt-in method. The plugin sends an email with the subscription confirmation link to the user and if the user confirms the subscription, it sends a welcome email to each new subscriber. The details of new subscribers are saved to the internal WordPress database. You can <a href="http://www.glockeasymail.com/wordpress-email-newsletter-plugin-for-double-opt-in-subscription/" title="create double opt-in mailing list">manage the mailing list inside WordPress</a> and export the list for the further use in your <a href="http://www.glockeasymail.com/" title="bulk email marketing software">email marketing software</a>. You can also use the plugin to convert your blog RSS feed into an email newsletter and send it out to your subscribers. You can design the style and content of your email newsletter yourself and you can schedule your email broadcast weekly, monthly or as soon as you add a certain number of new posts to your blog. Please see the <a href="http://www.glockeasymail.com/wordpress-email-newsletter-plugin-for-double-opt-in-subscription/history/" title="Double Opt-In sidebar widget version history">VERSION HISTORY</a> for what's new and current bugfixes.
PHP
3
star
15

cheesebread

A delicious and easy to cook CDN file caching for offline development environments.
JavaScript
2
star
16

Kohana-IDE-Resources

Resources for Eclipse IDE and based to easily work with Kohana Framework
1
star
17

vim-gartz

Gartz's vim config and modules
1
star
18

dcn

Docker-Compose-Node
Shell
1
star
19

jscalendar

Playing around with a friends code challenge, did it in pure JS using only the chrome snippet.
JavaScript
1
star
20

redux-in-place

A component way to integrate Redux an React, provides a easy way to make components depends on redux store structure, by creating it on-fly.
JavaScript
1
star
21

EleicoesBrazilScraper

Scraper to get all information about results in the Brazilian elections
JavaScript
1
star
22

next-emitter

Many implementations of event emitter for JavaScript with performance comparison
JavaScript
1
star
23

Kohana-Attach-Profiler

A extension to the default KO3 profiller, that auto attach the profiller to result body.
PHP
1
star