DataBind JS - example

Databinding for Javascript. Example is based on databindjs library + jQuery integration example.

HTML

<script src="https://unpkg.com/[email protected]/lib/index.js"></script>
<div class="simple">
  <input type="text" class="input-value">
  <div class="output-value">
  </div>
  <pre class="console">&nbsp;</pre>
</div>
<hr>
<div class="complex">
  <input type="text" class="input-value">
  <div class="output-value">
  </div>
  <input type="text" class="current-time" size="40">
    <button class="unbind">
  Unbind form
  </button>
  <pre class="console">&nbsp;</pre>
</div>

<i>This is example of the simple bindings. For the more complex solution could be required not only bind but unbind as well. e.g. unbindFrom(simpleBidngin)</i>

JavaScript

/**
 * npm package databindjs
 * Extracted into JS fiddle with https://unpkg.com/[email protected]/lib/index.js
 */
$(document).ready(function () {
    // simple solution
    // Lets assume that there is just simple form (target)
    var simpleForm = {
        input: $('.simple .input-value'),
        output: $('.simple .output-value')
    };
    // And here is the simple model object (source)
    var model = {
    		text: 'initial value'
    };
    
    // Lets set two directional binding between [input] <-> [text]
    var simpleBinding = bindTo(simpleForm, () => model, {
        'input.val': 'text',  // bind to user input
        'output.text': 'text'  // simple region that will react on user input
    });
    // This command will sync values from source to target (from model to view)
    updateLayout(simpleBinding);
    subscribeToChange(simpleBinding, () => {
    		$('.simple .console').html(JSON.stringify(model));
    });
    // Just initialize console from default model state
    $('.simple .console').html(JSON.stringify(model));
    
    // ===== more is about initialization of the databindjs tool =====
    //complex solution
    // For the more complex solution there is introduced full model with supporting updates
    // The view form is still simple
    var complexForm = {
        input: $('.complex .input-value'),
        output: $('.complex .output-value'),
        currentTime: $('.complex .current-time'),
        unbind: $('.complex .unbind')
    };

		// This is complex ViewModel that holds state and populates view when state is changed. 
    function ViewModel() {
        this.state = {
             text: 'initial value',
             time: new Date().toISOString()
        }
        setTimeout(() => {
          // Here will be initialized simple updating state logic
          setInterval(() => { this.prop('time', new Date().toISOString()); }, 900);
          
          // Lets monitor ViewModel state into the view (for testing purposes)
         ...