-
Notifications
You must be signed in to change notification settings - Fork 222
Cookbook
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.
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.
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 valueAnd 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.
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.