evtmgr
Helper for managing event handlers
Installing
$ npm install evtmgr# or $ bower install evtmgr
Overview
Can be used with anything that emits an event:
addEventListener
addListener
attachEvent
addEvent
Specifically useful when:
- Adding/removing handlers on a lifecycle hook
- Adding handlers that use
bind
, and need to be removed - Conveniently remove all added handlers
Example
React provides a good use case.
;; { superprops; thisstate = pinned: false ; thisevtmgr = ; thisevtmgr; } { thisevtmgr; } { thisevtmgr; } { this; } { var style = {}; if thisstatepinned styleposition = 'fixed'; styletop = 0; else styleposition = 'absolute'; styletop = 100; return <menu style=style> /*...*/ </menu> ; }
API
register(obj, type, handler)
Register an event handler
obj
An object that emits an event
type
The event type
handler
The function that handles the event
Example
var EventEmitter = EventEmitter;var EventManager = ;var emitter = ;var manager = ; // Register a single handlermanager; // Register handlers for multiple eventsmanager;
unregister(obj, type, handler)
Unregister an event handler
obj
An object that emits an event
type
The event type
handler
The function that handles the event
Example
var EventEmitter = EventEmitter;var EventManager = ;var emitter = ;var manager = ; {} {} // Register handlersmanager; // Actually, don't want to handle barmanager;
attach
Attach registered event handlers to the objects for which they handle events
Attaching can only be done once, so subsequent calls will have no effect,
unless detach
is called.
Example
// Registration does nothing until attach is calledmanager;manager;// Now el.click() will be handled
detach
Detach registered event handlers from the objects for which they handle events
Example
// Attach all the event handlersmanager; // Once handlers are no longer wantedmanager;
License
MIT