Skip to content

Instantly share code, notes, and snippets.

@jimjeffers
Created December 5, 2010 16:12
Show Gist options
  • Select an option

  • Save jimjeffers/729200 to your computer and use it in GitHub Desktop.

Select an option

Save jimjeffers/729200 to your computer and use it in GitHub Desktop.
A simple data binder plugin for jQuery.
# DataBinder is an object attached to the window. You can pass a JSON object
# and HTML node to the bind method to bind the JSON object data to the
# attributes mapped in the HTML node's data-bindings attribute. Providing
# an attribute data-template will cause the function to run recursively on child
# nodes. To prevent child nodes from being overwritten you can also set a
# data-preserve attribute on a given node. This will re-append a given elements
# children after updating it's content.
#
# Here's an example of a template in HTML:
# --------------------------------------------------------------------------------
# <li class="endorsement" data-template="true">
# <img data-binding="src:image_path alt:user_name">
# <span class="user_name" data-bindings="content:user_name"></span>
# <span class="activty_description" data-bindings="content:description"></span>
# <span class="skill_name" data-bindings="content:skill_name"></span>.
# <span class="timestamp" data-bindings="content:timestamp"></span>
# </li>
#
# A simple usage scenario would work like this:
# --------------------------------------------------------------------------------
# var new_item = DataBinder.duplicate($('.endorsement:first-child'),
# {'user_name':"John Doe",
# 'description':"was voted down for",
# 'skill_name':"Gardening",
# 'timestamp':"24 seconds ago",
# 'image_path':'/tmp/35963d7.jpg'
# });
# new_item.removeClass('template')
# ...
# $(body).append(new_item)
jQuery.fn.dataBinder = (options) ->
class DataBinder
constructor: ->
@id = "main"
bind: (node,json) ->
node = $(node)
if this.checkForAttributeOnNode('data-template',node)
for child in node.children()
this.bind(child,json)
if node.attr('data-bindings')
bindings = node.attr('data-bindings').split(' ')
for binding in bindings
binding = binding.split(":")
attribute = binding[0]
data = binding[1]
if attribute == "content"
children = node.children() if this.checkForAttributeOnNode('data-preserve',node) || this.checkForAttributeOnNode('data-template',node)
node.html(json[data])
node.append(children) if children
else
node.attr(attribute,json[data])
duplicate: (node,json) ->
duplicate = node.clone()
this.bind(duplicate,json)
duplicate
checkForAttributeOnNode: (attribute,node) ->
typeof(node.attr(attribute)) != 'undefined'
window.DataBinder = new DataBinder()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment