Rich, declarative, custom events made easy! Don't just listen for 'click'.
npm install triggerThe easiest way to use rich, declarative custom events and clean up your event handling!
Download: [trigger.min.js][prod] or [trigger.js][dev]
[NPM][npm]: ``npm install trigger` `
Bower: bower install trigger`
[prod]: https://raw.github.com/nbubna/trigger/master/dist/trigger.min.js
[dev]: https://raw.github.com/nbubna/trigger/master/dist/trigger.js
[npm]: https://npmjs.org/package/trigger
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
`html
`
`javascript
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:
`javascript
trigger._.attr = 'data-trigger';
`
`html
``[invalid]: http://wheelcode.blogspot.com/2012/07/html-validation-is-bad.html