Skip to content

Instantly share code, notes, and snippets.

@meleyal
Created May 31, 2013 13:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meleyal/5684841 to your computer and use it in GitHub Desktop.
Save meleyal/5684841 to your computer and use it in GitHub Desktop.
###
**TextUpdater**: change the text of one or more elements when another element changes.
Usage:
<input data-updates="#price, #vat-price" data-price="40 €" data-vat-price="48 €">
<input data-updates="#price, #vat-price" data-price="80 €" data-vat-price="88 €">
$('[data-updates]').textUpdater()
Example 1:
$('[data-updates]').first().trigger('change')
<span id="price">40 €</span>
<span id="vat-price">48 €</span>
Example 2:
$('[data-updates]').last().trigger('change')
<span id="price">80 €</span>
<span id="vat-price">88 €</span>
###
# Class definition
class TextUpdater
constructor: (element, options) ->
@$element = $(element)
selector = @$element.attr('data-updates')
@selectors = ($.trim(s) for s in selector.split(','))
@listen()
listen: ->
@$element.on 'change', @onChange
onChange: (e) =>
@updateValue(selector) for selector in @selectors
updateValue: (selector) ->
key = selector.substr(1)
value = @$element.data(key)
$(selector).text(value)
# Plugin definition
$.fn.textUpdater = (option) ->
this.each ->
$this = $(this)
data = $this.data('textUpdater')
options = typeof option is 'object' && option
$this.data('textUpdater', new TextUpdater(this, options)) unless data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment