Created
December 11, 2012 15:40
-
-
Save monicao/4259422 to your computer and use it in GitHub Desktop.
Backbone Child Views
This file contains 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
# View support class. Put all view helpers here. | |
Support.View = (options) -> | |
@children = [] | |
Backbone.View.apply(this, [options]) | |
_.extend(Support.View.prototype, Backbone.View.prototype, { | |
### | |
# COMPOSITE VIEWS | |
# Ensures all event bindings are unbound when a child view is removed. | |
# Source: Backbone on Rails book | |
### | |
leave: -> | |
child_view.leave() for child_view in @children when child_view.leave | |
console.log "leaving #{this.cid}" | |
@model.unbind() if @model | |
@collection.unbind() if @collection | |
this.unbind() | |
this.remove() | |
renderChild: (view) -> | |
view.render() | |
@children.push(view) | |
view.parent = this | |
view.afterRender() if view.afterRender | |
appendChild: (view) -> | |
this.renderChild(view) | |
$(@el).append(view.el) | |
appendChild: (view, sub_container) -> | |
this.renderChild(view) | |
$(@el).find(sub_container).append(view.el) | |
renderChildInto: (view, container) -> | |
this.renderChild(view) | |
$(container).empty().append(view.el) | |
appendChildTo: (view, container) -> | |
this.renderChild(view) | |
$(container).append(view.el) | |
_removeFromParent: -> | |
@parent._removeChild(this) if @parent | |
_removeChild: (view) -> | |
@children.splice(@children.indexOf(view), 1) | |
}) | |
Support.View.extend = Backbone.View.extend |
This file contains 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
class MyParentView extends Support.View | |
template: JST["parent_template"] | |
initialize: -> | |
@collection.bind("add", this.addNewThing, this) | |
this.render() | |
render: => | |
$(@el).html(this.template()) | |
for thing in @collection.models | |
this.appendChild(new MyChildView(), "section#child_area") | |
class MyChildView extends Support.View | |
template: JST["child_template"] | |
render: | |
$(@el).html(this.template()) | |
parent = new MyParentView({collection: something}) | |
parent.leave() # will call leave() on the parent and on all child views. | |
# leave() will unbind any DOM and model listeners bound in the views. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment