Created
May 8, 2012 03:19
-
-
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
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
| # 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