Skip to content
This repository was archived by the owner on Jun 15, 2023. It is now read-only.

Cookbook

mehcode edited this page Jan 10, 2013 · 16 revisions

The following are a collection of proven recipes that are too small to warrant an extension or a plugin but are not complete enough or too far out-of-scope to warrant inclusion in the core of Chaplin.

Simple (One-way) Data Binding

Problem

Traditionally binding via a micro-template can get messy; especially when if the model has not finished syncing with the server when the view is rendered. Re-rendering the view when the model updates is more of an anti-pattern as there could be a lot of structure that is needlessly re-created.

Solution

Add the follow method to your base class that extends Chaplin.View and is extended by your Views.

pass: (selector, attribute) ->
  return unless @model

  # Initially bind the current value of the attribute to 
  # the template (if we are rendered).
  $el = @$ selector
  $el.text @model.get attribute if $el

  # Then register a listener to respond to changes in the model
  # to keep the view in sync with the model.
  @listenTo @model, "change:#{attribute}", (model, value) =>
    @$(selector).text value

And call this method as follows in a view that derives from that base view.

initialize: ->
  @pass '.name', 'name'
  @pass '.phone', 'phone'

Which will set up 1-way data bindings for the model attributes name and phone to the DOM elements in the view with the classes .name and .phone respectively.

Limitations

This is limited to one-way binding and there isn't much allowance for complicated logic to generate the value, etc.

For a more complete solution, refer to Backbone.Stickit

Clone this wiki locally