Skip to content

Instantly share code, notes, and snippets.

@tomichj
Created April 15, 2015 20:21
Show Gist options
  • Save tomichj/48128af710fe53827ad3 to your computer and use it in GitHub Desktop.
Save tomichj/48128af710fe53827ad3 to your computer and use it in GitHub Desktop.
# Simple, light-weight data binding in coffeescript using jQuery.
# Simple, light-weight data binding using jQuery.
#
#
# Allows bi-directional data binding of DOM elements and/or JS objects.
#
# A dom element with [data-bind="key"], and it will publish changes
# and subscribe to changes from other elements bound to the same key.
#
# <input id="first_name" type="text" data-bind="firstname"/>
#
# <span data-bind="firstname"/>
#
# $.subscribe 'firstname', (event, a, b)->
# console.log a, b
#
#
# # Start typing in the input field, the span is updated and a log is written to console.
#
# The ultra-light publish/unsucribe/subscribe plugins come from https://github.com/cowboy/jquery-tiny-pubsub
#
(($) ->
o = $({})
$.subscribe = ->
o.on.apply o, arguments
return
$.unsubscribe = ->
o.off.apply o, arguments
return
$.publish = ->
o.trigger.apply o, arguments
return
class DataBinding
constructor: (element) ->
@$element = $(element)
key = @$element.attr('data-bind')
hasVal = @$element.is('select, option, input, textarea')
keyup = @$element.is('input, textarea')
valueMethod = if hasVal then 'val' else 'html'
triggerEvent = if keyup then 'keyup' else 'change'
# subscribe to changes to my key, update myself with those changes
$.subscribe key, (event, value, source)=>
@$element[valueMethod](value) unless @$element == source
# listen for changes to my @$element and publish change
@$element.on triggerEvent, (event)=>
$.publish(key, [@$element[valueMethod](), @$element])
$.fn.data_bind = ->
data_bind = $.data(@, 'data_bind')
data_bind = $.data(@, 'data_bind', new DataBinding(@)) unless data_bind
) window.jQuery
$(document).on 'page:update', ->
$('[data-bind]').each(-> $(this).data_bind())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment