Skip to content

Instantly share code, notes, and snippets.

@BlakeWilliams
Created May 8, 2012 03:19
Show Gist options
  • Select an option

  • Save BlakeWilliams/2632284 to your computer and use it in GitHub Desktop.

Select an option

Save BlakeWilliams/2632284 to your computer and use it in GitHub Desktop.
Coffeescript replacement for Backbone.Router and Backbone.View to add a swappable router with managed children in views
# Add swap method to router
_.extend Backbone.Router.prototype,
swap: (newView) ->
@currentView.leave() if @currentView && @currentView.leave
@currentView = newView
$(@el).html @currentView.render().el
# set original Backbone.View reference
view = Backbone.View
# Initialize children
managedView = (options) ->
@children = {}
view.apply(this, [options])
_.extend managedView.prototype, view.prototype,
leave: ->
@trigger('leave')
@unbind()
@remove()
@leaveChildren()
addChild: (name, view) ->
@children[name] = view
view.parent = this
renderChild: (name, el) ->
@$(el).html @children[name].render().el
@children[name]
leaveChildren: ->
_.each @children, (view, name) =>
view.leave()
@removeChild name
removeChild: (name) ->
@children[name] = {}
delete @children[name]
Backbone.View = managedView
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment