Skip to content

Instantly share code, notes, and snippets.

@markandrewj
Forked from k2052/simpleDataBinder.coffee
Last active August 29, 2015 14:14
Show Gist options
  • Save markandrewj/fcb6c73f5beefb0ecdb7 to your computer and use it in GitHub Desktop.
Save markandrewj/fcb6c73f5beefb0ecdb7 to your computer and use it in GitHub Desktop.
class DataBinder extends jQuery
pubSub: null
constructor: (objectid) ->
@pubSub = $ {}
attribute = "data-bind-#{objectid}"
message = "#{objectid}:change"
$(document).on "change", "[#{attribute}]", (event) =>
$elem = $(event.target)
@pubSub.trigger message, [$elem.attr(attribute), $elem.val()]
@pubSub.on message, (event, property, new_val) ->
for elem in $("[#{attribute}=#{property}]")
$elem = $(elem)
if $elem.is("input, textarea, select")
$elem.val new_val
else
$elm.html new_val
class Cat
binder: null
pubSub: null
message: ''
set: (attr, val) ->
@[attr] = val
@pubSub.trigger @message, [attr, val]
get: (attr) ->
@[attr]
constructor: (id) ->
@binder = new DataBinder(id)
@pubSub = @binder.pubSub
@message = "#{id}:change"
@pubSub.on @message, (event, attr, value) =>
@[attr] = value
cat = new Cat("cat-1")
cat.set("name", "Wiswell")
# HTML <input type="text" data-bind-cat-1="name" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment