You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
mehcode edited this page Jan 14, 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 Data Binding
Problem
Traditionally binding via a micro-template can get messy; especially 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) ->returnunless@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.
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.