A utility to setup DRY event listeners.
npm install dry-observer
|16||downloads in the last month|
|Version||0.2.2 last updated a year ago|
|Keywords||events observer backbone eventemitter|
Dryly bind and unbind event listeners and encourage consistent, pattern-based naming of handlers/callbacks.
# Observe a Model by passing a hash… @observe model, 'song:change' : @onSongChange 'volume:change' : @onVolumeChange 'focus' : @onFocus # …or a String or Array. # Observation will camelCase and prefix your events. @observe model, 'song:change volume:change focus' # Stop observing and dereference your model… @stopObserving model # …or stop observing /everything/ @stopObserving() # …or remove a specific handler and cleanup. @removeObserver model, 'song:change', @onSongChange
If you're working a lot with Backbone (or other EventEmitter-based APIs), you may have written or reviewed code that's similar to this:
There a number of problems with this code:
- Events aren't named or formatted uniformly.
- Handlers aren't consistently named, and may or may not rely on arguments passed
- Repetitive calls to
#offon different objects adds unDRY cruft to your codebase and…
- It's easy to forget to bind or unbind events, or update the names of your handlers as you go.
Observation helps you solve each of these problems by allowing you to centralize both binding and unbinding to events, and by encouraging consistent handler naming.
To fully leverage the usefullness of Observation, create a base subclass of Backbone.View you can use to ensure that event listeners always get cleaned up upon view removal.