Skip to content

Instantly share code, notes, and snippets.

@adamrneary
Created August 8, 2013 21:16
Show Gist options
  • Save adamrneary/6188833 to your computer and use it in GitHub Desktop.
Save adamrneary/6188833 to your computer and use it in GitHub Desktop.
# Base class for all views which display dynamically
#
# Backbone.js still does not have convenient way for avoiding memory leaks
# This class added this functionality. Most of the code inspired by backbone.marionette
#
# Examples:
#
# # Way to add subview in current view
# # When router will remove this view all nested/sub view will be remove automatically
# @createView SubView, collection: @something
#
# # Convinient way to add event-listener
# # on remove all events will be off and we don't get zombies
# @addEvent @model, 'change', @dosomething
#
# For more information:
# https://gist.github.com/1288947
# http://stackoverflow.com/questions/7567404/backbone-js-repopulate-or-recreate-the-view/7607853#7607853
# https://github.com/marionettejs/backbone.marionette
module.exports = class View extends Backbone.View
constructor: (options = {}) ->
super
# Add view render callbacks
# @see http://fahad19.tumblr.com/post/28158699664/afterrender-callback-in-backbone-js-views
@render = _.wrap @render, (render, options) =>
@beforeRender()
render(options)
@afterRender()
@
render: =>
@$el.html @template?()
@
beforeRender: =>
afterRender: =>
$("a[rel=popover]").popover().click( (e) -> e.preventDefault() )
createView: (klass, attrs) ->
view = new klass(attrs)
@views ||= []
@views.push view
view
removeViews: ->
view.remove() for view in @views
remove: ->
# Dispose all children
@removeViews() if @views
# Uses the default Backbone.View.remove() method which removes this.el from the DOM and removes DOM events.
super
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment