Created
November 9, 2012 15:48
-
-
Save jergason/4046427 to your computer and use it in GitHub Desktop.
Better Child Views in Backbone
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Base view class that all views extend | |
# NOTE: This is from real production code, so it has some messiness for | |
# dealing with real production issues. | |
View = Backbone.View.extend | |
initialize: (@model) -> | |
@render | |
super | |
# Makes it easy to have child views. Just create a container: <div class="bob"></div> | |
# then call @child '.bob', new Bob() | |
# or: @bob = new Bob(); @child '.bob', @bob | |
# WARNING: make sure to call super in your destroy method if you have one | |
child: (selector, view) -> | |
@autoChildren = @autoChildren || {} | |
# this will remove any old child, because destroy calls remove | |
@destroyChild(selector) | |
# set the container and save the view for destruction later | |
$container = @$el.find(selector) | |
if !$container.length | |
throw new Error "Could not find container: #{selector}" | |
$container.append view.$el | |
@autoChildren[selector] = view | |
destroyChild: (selector) -> | |
if (@autoChildren && @autoChildren[selector] && @autoChildren[selector].destroy) | |
@autoChildren[selector].destroy() | |
delete @autoChildren[selector] | |
destroy: -> | |
return if @destroyed | |
# destroy any children | |
@destroyChild selector for selector, view of @autoChildren | |
@autoChildren = null | |
@off() | |
@$el.remove() # it is somewhat important that the el is removed after all children have been destroyed | |
@destroyed = true | |
# use like this, assuming we have these other views in scope | |
class SomeChild extends View | |
initialize: -> (@model) | |
# Initialize and append child views. They will automatically get cleaned up when you call SomeView.destroy() | |
@child '.hurp', new HurpView @model | |
@child '.durp', new DurpView | |
super |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment