Skip to content

Instantly share code, notes, and snippets.

@k2052
Last active December 31, 2015 16:19
Show Gist options
  • Select an option

  • Save k2052/8012927 to your computer and use it in GitHub Desktop.

Select an option

Save k2052/8012927 to your computer and use it in GitHub Desktop.

Revisions

  1. k2052 revised this gist Dec 17, 2013. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions simpleDataBinder.coffee
    Original file line number Diff line number Diff line change
    @@ -3,7 +3,7 @@ class DataBinder extends jQuery

    constructor: (objectid) ->
    @pubSub = $ {}
    attribute = "bind-#{objectid}"
    attribute = "data-bind-#{objectid}"
    message = "#{objectid}:change"

    $(document).on "change", "[#{attribute}]", (event) =>
    @@ -42,4 +42,4 @@ class Cat
    cat = new Cat("cat-1")
    cat.set("name", "Wiswell")

    # HTML <input type="text" bind-cat-1="name" />
    # HTML <input type="text" data-bind-cat-1="name" />
  2. k2052 created this gist Dec 17, 2013.
    45 changes: 45 additions & 0 deletions simpleDataBinder.coffee
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@
    class DataBinder extends jQuery
    pubSub: null

    constructor: (objectid) ->
    @pubSub = $ {}
    attribute = "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" bind-cat-1="name" />