Skip to content

Instantly share code, notes, and snippets.

@wbbradley
Last active December 17, 2015 13:28
Show Gist options
  • Save wbbradley/5616953 to your computer and use it in GitHub Desktop.
Save wbbradley/5616953 to your computer and use it in GitHub Desktop.
Base View classes for Backbone fundamentals...
###
# Backbone views
###
#
# Handling subviews:
# http://stackoverflow.com/questions/9337927/how-to-handle-initializing-and-rendering-subviews-in-backbone-js
# Basic render strategy:
# http://ianstormtaylor.com/rendering-views-in-backbonejs-isnt-always-simple/
handlebars_render = (template_name, context) ->
template = App.Handlebars[template_name]
console.log 'Rendering template \'' + template_name + '\''
output = template context
return output
render = handlebars_render
# BasicModelView always updates and is therefore only OK for basic templates
# that are not nested or involving forms.
class BasicModelView extends Backbone.View
render: =>
context =
model: @model.toJSON()
url: @model.url
template_result = render @template, context
# console.log 'BasicModelView : info : rendered "' + template_result + '"'
@$el.html(template_result)
@
initialize: =>
@render()
@listenTo @model, 'change', @render
class CompositeModelView extends Backbone.View
_rendered: false
render: =>
if @_rendered
# CompositeModelView should not need to render multiple times since it is
# associated with a model and not individual fields
return @
@_rendered = true
context =
model: @model.toJSON()
url: @model.url
template_result = render @template, context
@$el.html(template_result)
@
initialize: =>
console.log 'CompositeModelView created'
@render()
for binding, view of _.result(@, 'child_views')
@[binding] = if typeof view is 'function' then view() else view
class ModelFieldView extends Backbone.View
get_value: => _.result(@model.toJSON(), @options.property)
render: =>
value = @options.model.get(@options.property)
context = {}
context[@options.property] = value
template_result = render @options.template, context
@$el.html(template_result)
@
initialize: (options) =>
if @options.is_form_field
@listenToOnce @options.model, 'change:' + @options.property, @render
else
@render()
@listenTo @options.model, 'change:' + @options.property, @render
class BaseCollectionView extends Backbone.View
initialize: (options) =>
if not options.item_view_class
throw 'no child view constructor provided'
@_childViews = []
@collection.each @add
@listenTo @collection, 'add', @add
@listenTo @collection, 'remove', @remove
add: (model) =>
childView = new @options.item_view_class
model: model
@_childViews.push childView
@$el.append(childView.render().el)
remove: (model) =>
viewToRemove = (_(@_childViews).select (cv) => return cv.model == model )[0]
@_childViews = _(@_childViews).without(viewToRemove)
@$(viewToRemove.el).remove()
###############################################
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment