• This repository has been archived on 22/Jan/2019
  • Stars
    star
    211
  • Rank 186,797 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 11 years ago
  • Updated about 9 years ago

Reviews

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

Repository Details

Event Driven JS

Event Driven JS

a not so obtrusive and highly optimized attempt to make JavaScript more awesome than ever!

build status

NPM

Now in cdnJS

Many thanks to cdnjs for hosting this script. Following an example on how to include it.

<script
  src="//cdnjs.cloudflare.com/ajax/libs/eddy/0.6.3/eddy.dom.js"
>/* eddy.js */</script>

In order to have a fully patched environment for older browser too, we could include these scripts too:

<!--[if IE 8]><script
  src="//cdnjs.cloudflare.com/ajax/libs/ie8/0.2.3/ie8.js"
></script><![endif]-->
<script
  src="//cdnjs.cloudflare.com/ajax/libs/dom4/1.0.1/dom4.js"
>/* DOM4 */</script>
<script
  src="//cdnjs.cloudflare.com/ajax/libs/eddy/0.6.3/eddy.dom.js"
>/* eddy.js */</script>

The eddy.js Philosophy

It does not matter if you code client or server side, we all need the same thing and we keep using this or that library to obtain the same behavior.

I am talking about all de-facto standards API such .on(type, handler), .once(type, handler), .off(type, handler) together with .emit(type, arg1, argN) and .listeners(type) or .trigger(type, detail) to deal with DOM nodes.

eddy.js aim is to harmonize all these API at core level polluting in a non enumerable way the Object.prototype in a smart way that simply works!

This means no worries at all for any for/in loop you might have in there, even in IE.

As summary, this is the philosophy behind this module

eddy.js is a very pragmatic approach, back those days where developers enriched native prototypes to do more with less code ;-)

Compatibility

eddy.js is tested and compatible with the following mobile platforms

  • iOS 5, 6, 7+
  • Android 2.2+, 3, 4.0, 4.1, 4.2, 4.3+
  • Windows Phone 7, 8+
  • FirefoxOS 0.X, 1+
  • Blackberry 10 (probably older too, haven't tested yet)
  • Opera Mini, Opera Mobile, and Opera Mobile Beta
  • webOS 2+
  • Nokia Asha and Nokia Xpress browser
  • UC Browser for Android 2.X or higher

eddy is also compatible with the following desktop browsers

  • Chrome, Canary, and Chromium channel
  • Safari 5+ and Webkit Nightly
  • Internet Explorer 8, 9, 10, 11+
  • Firefox, Aurora, and Nightly channel
  • Opera

In order to verify your browser too please visit the test page.

Last, but not least, eddy.js has been used and tested in the following server side platforms

  • node.js
  • rhino

If you clone the repo, just make test for node or be sure you have a stable rhino jar and java -jar /path/to/that/jar/js.jar testrhino.js.

Object.prototype Enriched API

Here a list of methods you can use by default in an eddy.js environment.

Object#on(type, handler[, capture])

Returns the object itself after adding an event handler. This is basically the equivalent of addListener or addEventListener, where duplicated handlers for the same event are not allowed.

var stopWatch = {
  startTime: Date.now()
}.on(
  'change',
  function () {
    // log elapsed time per each change
    console.log(Date.now() - this.startTime);
  }
);

setInterval(function () {
  stopWatch.emit('change');
}, 10);

// or using the boundTo method
// and the extra arguments accepted by setInterval
setInterval(stopWatch.boundTo('emit'), 10, 'change');

The handler can be either a function or an object as it is for DOM methods such addEventListener or removeEventListener. In this case the method handleEvent is invoked with the object itself as context as it is for the native DOM behavior.

The third boolean capture argument is useless with JS objects but might be used in some DOM specific case. By default, capture is false.

Object#once(type, handler[, capture])

Similar to Object#on(type, handler[, capture]), except the event is triggered once and never again unless specified later on.

// on a generic HTML page inside a script tag...
this.once('load', function(e) {
  console.log('page fully loaded');
  // even if triggered manually
  // this event won't fire anymore
  this.fire('load');
  // nothing happened
});

Please read the note about .off before chosing this method.

Object#off(type, handler[, capture])

Returns the object itself after removing an event handler, if present. This is basically the equivalent of removeListener or removeEventListener.

function clearAllEntries() {
  database.clear();
}
window.on('unload', clearAllEntries);
keepEntriesButton.on('click', function () {
  // drop the clear procedure
  window.off('unload', clearAllEntries);
});
Note about .off and .once

Please note that in case .once was used, instead of .on, this method will not remove the listener. Accordingly, if you need to eventually drop later on a listener via .off, use .on and not .once.

Object#trigger(type[, detail])

Triggers / fires all handlers associated to the event type enriching the event with arbitrary detail simulating what CustomEvent does in DOM Level 4 specifications.

This method is more suitable for DOM events or those events based on a single argument parameter/object.

window.onresize = function (e) {
  alert(e.detail); // object {any:'detail'}
};
window.trigger('resize', {any:'detail'});

In the DOM world, it is possible to use directly .trigger(new CustomEvent(type, {cancelable:true, bubbles: true, detail: anyData})).

This method will return false if any listener called event.preventDefault() since by default all triggered events will be cancelable.

Object#emit(type[, arg1][, argN])

This method behaves like node.js one, accepting one or more optional arguments after the type.

var object = {}
  .on('modify', function (key, value) {
    this[key] = value;
  })
  .on('delete', function (key) {
    delete this[key];
  })
;
object.emit('modify', 'key', Math.random());
console.log(object.key); // 0.3245979759376496
object.emit('delete', 'key');
console.log(object.key); // undefined

In the DOM world this method will dispatch an event with specified type and an arguments property for interoperability purpose. Such property will contain optional extra arguments used to .emit(type, a1, aN) in first place.

Object#listeners(type)

This method behaves like node.js one but on DOM object it will always return an empty array-like object.

function handler() {}
var obj = {}.on('event', handler);
var listeners = obj.listeners('event');

console.log(listeners[0] === handler); // true

In the DOM world there's no way to retrieve back nodes and it has never been a real problem but for node.js or generic JS business logic the possibility to understand already added listeners might be handy (I needed this in dblite and I've realized it is a very handy method!)

Object#boundTo(method)

This method creates a single bound version of the generic function or instance method.

var obj = {
  test: function () {
    console.log(this === obj);
  }
};
console.log(
  obj.boundTo('test') === obj.boundTo('test')
); // true
obj.boundTo('test')(); // true

If the argument is a function instead of a string that function is used instead.

function test() {
  console.log(this === obj);
}
var obj = {};
console.log(
  obj.boundTo(test) === obj.boundTo(test)
); // true
obj.boundTo(test)(); // true

Same thing if we pass the method itself as function instead of method name:

var obj = {
  test: function () {
    console.log(this === obj);
  }
};
console.log(
  obj.boundTo(obj.test) === obj.boundTo('test')
); // true

since version 0.5.2

The boundTo method now is able to set, if not already present, a method to a generic object.

var fn = function(){return this};
obj.boundTo('test', fn) === obj.boundTo('test', function(){})
obj.boundTo('test', fn)() === obj
obj.test === fn

This can be very useful for runtime, in scope, function addressing as example for DOM handlers.

Object#expect(type1, ..., typeN)

Prepares upfront the generic object to accept later on when calls so that it's not needed to when with empty listeners anymore but just declare through this method what might be emitted/dispatched/triggered later on.

var myApp = new MyApp().expect(
  'geolocation',
  'filePermission',
  'fullScreen'
);

navigator.geolocation.getCurrentPosition(
  function(info) {
    myApp.emit('geolocation', info);
  }
);

// ... later on ...
myApp
  .when('geolocation', function (info) {
    // map it
  })
  .when('filePermission', function (file) {
    // upload it
  })
  .when('fullScreen', function (err, ok) {
    if (ok) ;// show it!
  })
;

Object#when(type, handler)

This method simply provides a way to retrieve some data the very first time it has been triggered.

Please note this is not an equivalent to Promises/A+, the one implemented in next version of JavaScript, neither when library, this is just meant to simplify few common cases in an Event_ish_ way.

// async, who knows if and when it will happen
// will be asked only once in any case (not a watchPosition)
navigator.geolocation.getCurrentPosition(
  function(info) {
    myApp.emit('geocurrentposition', null, info);
  },
  function(err) {
    myApp.emit('geocurrentposition', err || 'unknown', null);
  }
);


// wait to retrieve initial position
myApp.when('geocurrentposition', function(err, pos) {
  if (err) {
    console.error('' + err);
  } else {
    console.log(pos.coords);
  }
});

// any other object could listen even if resolved
// it wan't ask again for the position

Above example could be extended to database access request or any other classic user operation that should not be asked more than once, decoupling different requests independently.

document.when("ready", callback)

This is a very special case featured directly in core. Inspired by the most famous $(document).ready(callback) behavior, document.when("ready", callback) acts exactly the same way.

If you load eddy.dom.js lazily, this should work in any case even after the DOMContentLoaded and for all supported browsers.

// even if lazily loaded
document.when('ready', function(e){
  console.log('we are ready to go');
});

// later, even loaded asynchronously and without AMD
document.when('ready', initLibrary);

This will ensure that the event will be available whenever a script will ask to listen for the ready event.

Please note that if the document is already ready, this will be fired asynchronously and ASAP but never inline.

DOM Only

In order to make life easier on DOM world too, there are few extra methods on top of regular eddy stuff, including same behavior for XMLHttpRequest.

DOM#data(key[, value])

This method is a normalizer for the dataset magic attributes behavior with one exception: you can simply assign null or undefined to remove the attribute when and if not needed anymore.

var div = document.createElement('div');
div.data('key', 'value');
div.hasAttribute('data-key'); // true
div.data('key'); // 'value'
div.data('key', null);
div.hasAttribute('data-key'); // false

Array.prototype Enriched API

New in version 0.3, all Array.prototype methods but boundTo and listeners have been made smart enough to perform the same call inside each item of the array.

This approach simplifies a very common pattern with collections, specially in the DOM world, so that we can add or remove events to many objects at once.

function $(CSS, parentNode) {
  // @link http://webreflection.blogspot.com/2014/05/134-bytes-for-optimized-and-very-basic.html
  var el = parentNode || document,
      first = CSS.lastIndexOf(':first') === CSS.length - 6,
      query = first ?
        el.querySelector(CSS.slice(0, -6)) :
        el.querySelectorAll(CSS);
  return first ?
    (query ? [query] : []) :
    Array.prototype.slice.call(query);
}

// later on ...
$('ul > li').on('click', doStuff);

The assumption is that collections are commonly used like that.

Which File ?

eddy.js comes in different flavors but it operates on global, native, constructors. This means once you require or include or load eddy.js you need to manually delete polluted prototypes if needed. Anyway, here the list of files you need:

  • browser without DOM, for browsers meaning down to IE6 baby, fear not!
  • browser with DOM, for browsers meaning IE8, using ie8 file plus all modern mobile and desktop browsers. In order to have an almost fully standard and updated DOM environment, please add dom4 after ie8 as done as example in the test page.
  • AMD including DOM, same as eddy.dom.js inside the require AMD logic. Both ie8 and dom4 are strongly suggested here too.
  • node.js, meaning node.js and other server side engines since no export is used/needed

You can install eddy.js directly via npm install eddy too and simply use require('eddy'). The version for node should work for Rhino too without problems ;-)

Why Eddy As Name ?

Not only because of the " Event Driven sound check ", the definition I prefer is the following one:

a current or trend, as of opinion or events, running counter to the main current.

but all other definitions are somehow very metaphoric too ;-)

Not Your Meal ?

If you are stuck in late 90s dogmas about JS and forbidden Object.prototype pollution, you can always go for EventTarget mixin and use that with all your classes.

What eddy.js gives you here, is the ability to forget all these problems and use emitters when you need them, if you need them, as easy as that.

More Repositories

1

hyperHTML

A Fast & Light Virtual DOM Alternative
HTML
3,028
star
2

linkedom

A triple-linked lists based DOM implementation.
HTML
1,156
star
3

document-register-element

A stand-alone working lightweight version of the W3C Custom Elements specification
JavaScript
1,131
star
4

dom4

Modern DOM functionalities for every browser
JavaScript
929
star
5

flatted

A fast and minimal circular JSON parser.
JavaScript
893
star
6

url-search-params

Simple polyfill for URLSearchParams standard
JavaScript
765
star
7

uhtml

A micro HTML/SVG render
JavaScript
707
star
8

lighterhtml

The hyperHTML strength & experience without its complexity πŸŽ‰
JavaScript
702
star
9

JSONH

Homogeneous Collection Compressor
JavaScript
618
star
10

circular-json

JSON does not handle circular references. Now it does
JavaScript
599
star
11

viperHTML

Isomorphic hyperHTML
JavaScript
318
star
12

heresy

React-like Custom Elements via V1 API builtin extends.
JavaScript
271
star
13

es6-collections

Map, WeakMap, and Set fast/simple shim for Harmony collections
JavaScript
253
star
14

neverland

React like Hooks for lighterhtml
JavaScript
241
star
15

wicked-elements

Components for the DOM as you've never seen before
JavaScript
235
star
16

dblite

sqlite for node.js without gyp problems
JavaScript
209
star
17

domdiff

Diffing the DOM without virtual DOM
JavaScript
197
star
18

hyperHTML-Element

An extensible class to define hyperHTML based Custom Elements.
JavaScript
195
star
19

benja

Bootable Electron Node JS Application
194
star
20

uce

Β΅html based Custom Elements
JavaScript
183
star
21

usignal

A blend of @preact/signals-core and solid-js basic reactivity API
JavaScript
176
star
22

highlighted-code

A textarea builtin extend to automatically provide code highlights based on one of the languages available via highlight.js
HTML
172
star
23

restyle

JavaScript
167
star
24

testardo

a browser and OS agnostic web driver for mobile and desktop
JavaScript
166
star
25

sqlite-worker

A simple, and persistent, SQLite database for Web and Workers.
JavaScript
159
star
26

augmentor

Extensible, general purpose, React like hooks for the masses.
JavaScript
135
star
27

uhooks

micro hooks: a minimalistic client/server hooks' implementation
JavaScript
127
star
28

polpetta

Polpetta, any folder is served spiced
JavaScript
125
star
29

basicHTML

A NodeJS based, standard oriented, HTML implementation.
JavaScript
123
star
30

udomdiff

An essential diffing algorithm for Β΅html.
JavaScript
117
star
31

pocket.io

A minimalistic version of socket.io that weights about 1K instead of 60K.
JavaScript
112
star
32

caller-of

The tiniest yet most powerful JS utility ever :D
HTML
102
star
33

uland

A Β΅html take at neverland
JavaScript
101
star
34

uce-template

A Vue 3 inspired Custom Elements toolless alternative.
JavaScript
100
star
35

json.hpack

JSON Homogeneous Collections Packer
C#
95
star
36

wru

essential unit test framework
JavaScript
95
star
37

html-escaper

A module to escape/unescape common problematic entities done the right way.
JavaScript
95
star
38

udomsay

A stricter, signals driven, ESX based library
JavaScript
95
star
39

db

JavaScript
94
star
40

import.js

A dynamic import() polyfill
JavaScript
93
star
41

regular-elements

Custom Elements made available for any node, and through CSS selectors
JavaScript
91
star
42

proxy-pants

Secured and reliable Proxy based utilities for more or less common tasks.
JavaScript
90
star
43

ucompress

A micro, all-in-one, compressor for common Web files.
JavaScript
90
star
44

archibold.io

archibold.io
Shell
85
star
45

jsgtk

A simplified approach to GJS for Node.JS and JavaScript developers.
JavaScript
85
star
46

heresy-ssr

πŸ”₯ heresy πŸ”₯ Server Side Rendering
JavaScript
84
star
47

hypersimple

The easiest way to use hyperHTML
JavaScript
83
star
48

asbundle

A minimalistic JS bundler
JavaScript
77
star
49

introspected

Introspection for serializable arrays and JSON friendly objects.
HTML
77
star
50

node-gtk

GNOME Gtk+ bindings for NodeJS
C++
74
star
51

i18n-utils

The i18n tag function utilitities
JavaScript
73
star
52

viper-news

viperHTML version of the Hacker News app.
JavaScript
72
star
53

ucdn

A Β΅compress based CDN utility, compatible with both Express and native http module
JavaScript
67
star
54

electroff

A cross browser, electron-less helper, for IoT projects and standalone applications.
JavaScript
64
star
55

builtin-elements

A zero friction custom elements like primitive.
JavaScript
62
star
56

nonchalance

The easiest way to augment DOM builtin elements.
JavaScript
61
star
57

universal-mixin

A mixin usable for both generic objects and decorators.
JavaScript
59
star
58

attachshadow

An iframe based Shadow DOM poorlyfill
JavaScript
59
star
59

ucontent

An SSR HTML content generator.
JavaScript
58
star
60

dom-augmentor

Same as augmentor but with DOM oriented useEffect handling via dropEffect.
JavaScript
56
star
61

ascjs

ES2015 to CommonJS import/export transformer
JavaScript
55
star
62

geo2city

Basic offline reverse geocode
JavaScript
53
star
63

vanilla-elements

A Minimalistic Custom Elements Helper.
JavaScript
51
star
64

wrist

Minimalistic utility for generic one/two ways data bindings.
HTML
51
star
65

screenfit

A cross platform, cross WebView, solution to fit 100% any Web page.
HTML
50
star
66

html-parsed-element

A base custom element class with a reliable `parsedCallback` method.
HTML
50
star
67

sqlite-tag

Template literal tag based sqlite3 queries.
JavaScript
49
star
68

jsdon

A DOM serializer based on LinkeDOM idea
HTML
48
star
69

echomd

A terminal oriented MD like syntax
JavaScript
48
star
70

dom-class

A lightweight, cross browser, simplification of WebComponents.
JavaScript
46
star
71

cloner

Cloning ES5+ objects in a shallow or deep way
JavaScript
46
star
72

css-proxied-vars

The easiest way to set, read, or update, CSS variables per each element.
JavaScript
46
star
73

event-target

The EventTarget Class Polyfill.
HTML
46
star
74

hn

Isomorphic Hacker News
JavaScript
45
star
75

proxied-worker

A tiny utility to asynchronously drive a namespace exposed through a Worker.
JavaScript
45
star
76

Database

Web SQL Storage Made Easy
JavaScript
44
star
77

promise

Abortable and Resolvable Promises.
JavaScript
43
star
78

poorlyfills

Simplified, partial, and poor ES6 collections polyfills, targeting IE9+ and older mobile browsers.
HTML
43
star
79

babel-plugin-transform-builtin-classes

A fix for the infamous Babel #4480 bug.
JavaScript
43
star
80

redefine

lightweight utility for smart object properties definition
JavaScript
42
star
81

nativeHTML

coming soon
JavaScript
42
star
82

bidi-sse

Bidirectional Server-sent Events
JavaScript
42
star
83

domtagger

The hyperHTML's template literal parser
JavaScript
41
star
84

hooked-elements

wickedElements πŸ§™ with render hooks
JavaScript
41
star
85

classtrophobic

Breaking JS Class Constrains
HTML
41
star
86

a-route

Express like routing as Custom Element or standalone
JavaScript
40
star
87

header-snippets

A collection of snippets to put in your header.
HTML
40
star
88

life-diary

your albums, your journey, your data
JavaScript
40
star
89

static.email

The easiest way to send emails on the Web
JavaScript
39
star
90

lazytag

Lazy loading Custom Elements and their styles without even thinking about it.
JavaScript
38
star
91

es-class

ECMAScript 3 to 6 compatible Class definition
JavaScript
38
star
92

tiny-cdn

A tiny static files serving handler
JavaScript
37
star
93

broadcast

Notification channel for the past, the present, and the future.
JavaScript
37
star
94

p-cool

Pretty Cool Elements
JavaScript
36
star
95

monthly

A simplified way to show a calendar month in any console.
HTML
36
star
96

jsx2tag

Enable JSX for Template Literal Tags based projects.
JavaScript
36
star
97

consolemd

Bringing echomd to console.
JavaScript
36
star
98

common-js

CommonJS + module.import() for any Browser
JavaScript
35
star
99

qsa-observer

handle elements lifecycle through CSS selectors
JavaScript
35
star
100

create-viperhtml-app

A basic viperHTML + hyperHTML setup
JavaScript
35
star