Created
May 31, 2013 13:03
-
-
Save meleyal/5684841 to your computer and use it in GitHub Desktop.
This file contains 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
### | |
**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