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 # You can even pass multiple events per callback… @observe collection, 'add remove reset': @render
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.