Skip to content

Instantly share code, notes, and snippets.

@bewest
Created April 29, 2012 22:04
Show Gist options
  • Save bewest/2553482 to your computer and use it in GitHub Desktop.
Save bewest/2553482 to your computer and use it in GitHub Desktop.
field descriptors
App.Views.FieldDescriptor = Backbone.View.extend(
###
FieldDescriptor automatically generates CSS selectors from a
a Model by iterating over keys found in Model.toJSON( ).
It binds to el passed to it using this basic template:
$prefix.$key .value, $prefix.$key.value
For most DOM nodes, we replace the text with the actual value.
For inputs, we replace the values. For inputs and checkboxes,
we set the control's checked property if the value is the same.
###
prefix: ''
initialize: ( ) ->
@model.on('change', _.bind(@render, @))
@render( )
render: ( ) ->
json = @model.toJSON( )
for own k, value of json
selector = "#{@prefix}.#{k} .value, #{@prefix}.#{k}.value"
results = @$(selector)
@$el.find(selector)
.filter(':input:not(:radio,:checkbox)').val(value).end( )
.filter(':input:radio, :input:checkbox')
.filter( (i, el) -> $j(el).val( ) == value ).prop('checked', true).end( ) .filter(':not(:input)').text(value)
@
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment