Last active
December 31, 2015 16:19
-
-
Save k2052/8012927 to your computer and use it in GitHub Desktop.
Simple Data Binding in CoffeeScript using jQuery. jsFiddle] at http://jsfiddle.net/L8JkR/2/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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