Skip to content

Instantly share code, notes, and snippets.

@wulftone
Created December 24, 2011 01:46
Show Gist options
  • Save wulftone/1515914 to your computer and use it in GitHub Desktop.
Save wulftone/1515914 to your computer and use it in GitHub Desktop.
Handy base class extensions for Backbone.View
# Credit goes to JonnyO from stackoverflow: http://stackoverflow.com/questions/7567404/backbone-js-repopulate-or-recreate-the-view/7607853
@BaseView = (options) ->
@bindings = []
Backbone.View.apply this, [ options ]
_.extend BaseView::, Backbone.View::,
# binds and keeps track of objects (models and collections) we want this view to respond to
bindTo: (model, event, callback) ->
model.bind event, callback, this
@bindings.push
model: model
event: event
callback: callback
# removes all bindings that were logged in the @bindings array
unbindFromAll: ->
_.each @bindings, (binding) ->
binding.model.unbind binding.event, binding.callback
@bindings = []
# cleans everything up so we don't have view objects and events hanging around in the DOM
dispose: ->
@unbindFromAll() # this will unbind all events that this view has bound to
@unbind() # this will unbind all listeners to events from this view. This is probably not necessary because this view will be garbage collected.
@remove() # uses the default Backbone.View.remove() method which removes this.el from the DOM and removes DOM events.
# I think this copies 'extend' functionality to BaseView
BaseView.extend = Backbone.View.extend
###################
## Sample usage: ##
###################
class SampleView extends BaseView
initialize: ->
@bindTo @model, "change", @render
@bindTo @collection, "reset", @doSomething
sampleView = new SampleView
model: some_model
collection: some_collection
sampleView.dispose()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment