EventStack
Event handling made easy using functional reactive programming and cross-browser consistent event models.
Installation
- You can install EventStack on node.js using the npm command
npm install event-stack
. - You can install EventStack for web apps using the component command
component install javascript/eventstack
. - You can install EventStack for web apps using the bower command
bower install eventstack
.
Usage
-
You can use EventStack as a CommonJS module:
var Events = require("event-stack");
var Keys = require("event-stack/Keys");
-
You can use EventStack with the AMD API:
define(["Events", "Keys"], function (Events, Keys) {
});
-
You can include the latest copy in your web pages, fiddles and benchmarks:
<script src="https://rawgithub.com/javascript/eventstack/master/Events.js"></script>
<script src="https://rawgithub.com/javascript/eventstack/master/Keys.js"></script>
-
You could use browserify to convert your node modules and their dependencies into a single JavaScript file, ready to be deployed onto the web.
Getting Started
EventStack makes use of functional reactive programming concepts to make working with events simple. Hence instead of writing monolithic event handlers you could work with simple event streams.
An event stream is a data structure which represents an infinite stream of events. Any object which implements a publish/subscribe model can expose an event stream interface. For example:
var Events = require("event-stack");
var domready = require("domready");
domready(function () {
var inputs = document.getElementsByTagName("input");
var output = document.getElementsByTagName("div")[0];
var a = Events.getEvents(inputs[0], "change");
var b = Events.getEvents(inputs[1], "change");
var c = a.merge(b).scan([0, 0], function (acc, e) {
var a = e.left || acc[0];
var b = e.right || acc[1];
return [a, b];
});
var sum = c.map(function (acc) {
var a = acc[0];
var b = acc[1];
var c = output.innerHTML = a + b;
return c;
});
var big = sum.filter(function (x) {
return x >= 100;
});
var small = sum.filter(function (x) {
return x < 100;
});
big.map(function (x) {
document.title = x + " is a big number.";
});
small.map(function (x) {
document.title = x + " is a small number.";
});
});
Make sure to check out the examples too. To build each example go to the example folder and run the following commands:
$ cd examples/keyboard-example
$ npm install
$ make
$ node server.js
Then simply go to your browser and open localhost:1337
. The keyboard example shows how to capture keyboard events and process them. Press any key in your browser and then see the server log the key to the console.
License
The EventStack library is released under the MIT license. So feel free to modify and distribute it as you wish.