trigger
v1.1.1
Published
Rich, declarative, custom events made easy! Don't just listen for 'click'.
Downloads
145
Readme
The easiest way to use rich, declarative custom events and clean up your event handling!
Download: trigger.min.js or trigger.js
NPM: npm install trigger
Bower: bower install trigger
Documentation
It's pretty simple; you add a trigger="foo""
to an element, when the
user "pulls it" (click or Enter keyup, as appropriate), your custom event
will fire automatically. You no longer have to manually translate clicks and
keyups in your app code. Your HTML becomes more readable and so does your javascript.
If that's not enough, doing trigger="validate save"
will trigger the "validate" and "save"
events in sequence. Your list of events can be as long as you like. To stop the sequence,
catch an event in it and call event.preventDefault()
or return false;
to prevent the rest of the events in the list from happening.
But wait, there's more! You probably want to distinguish your battleship's "explode" event from a mere
missile's "explode". Just add a namespace like so: trigger="explode.ship"
.
Your explosion listener can check the event.namespace
property.
Or perhaps you want to throw in a little contextual data: trigger="addTax['CA']"
As you guessed, it gets JSON parsed and stuck at event.data
.
You can even add simple tags to your events: trigger="yell#once#loud"
(see event.tags
and each event[tag]
).
Be warned, if you feel crazy enough to use awful (but rich and declarative) combinations of all three:
trigger="yell.player['howdy!']#loud"
, then you must put them in that namespaces, data, tags order.
Examples
<div id="#chutesAndLadders">
<input type="dice" name="roll">
<button trigger="move#up nextPlayer">Climb</button>
<button trigger="move#down nextPlayer">Slide</button>
</div>
var game = document.querySelector('#chutesAndLadders');
game.addEventListener('nextPlayer', function() {
player = player.next;
});
game.addEventListener('move', function(e) {
var distance = game.querySelector('[name=roll]').value;
if (e.up) player.climb(distance);
if (e.down) player.slide(distance);
if (player.hasWon()) e.preventDefault();//blocks nextPlayer event
});
If you, for some strange reason, care about "valid HTML", then you can do this:
trigger._.attr = 'data-trigger';
<button data-trigger="foo">Foo!</button>
But personally, I don't recommend it.
Release History
- 2010-04-02 v0.1 (internal release - jQuery plugin)
- 2012-09-13 v0.3 (internal release - declarative tags and data)
- 2013-05-03 v0.9.0 (public) - First GitHub release (sans jQuery integration)