Javascript Closures for Data Binding

Example of how to use javascript closures to perform data binding. Uses jQuery to make things clear. author(s): Michael Anderson

HTML

<script src="http://http://therobotsbrain.blogspot.com/"></script>
<h1>Test for binding data into dynamic forms using javascript closures</h1>
This creates multiple divs (with each click on the add button) and binds the contained control to
an element of the <code>data</code> array.

<br/><a id="add_button" href="#">Click me to add a new datum</a><br/>
<div id="target_div"></div>

<a id="show_data" href="#">Show Data</a>
<div id="data"></div>

JavaScript

$(document).ready( function() {
    $('#add_button').click( add_pane_with_data_binding );
    $('#show_data').click( show_data );
    } );

var data = [];

function add_pane_with_data_binding()
{
  //Add the data
  var this_data = { "v":"Hello World" };
  data.push( this_data );

  //Add view to the target div
  var this_div = $('<div></div>');
  var this_input = $('<input type="text"></input>');
  this_div.append( this_input );
  $('#target_div').append( this_div );
  this_input.val( this_data.v );
  
  //Now bind the change via a closure
  function on_change_function(e)
  {
    this_data.v = this_input.val();
  }

  this_input.bind('change',on_change_function);
}

function show_data()
{
    $('#data').html( '<pre>'+JSON.stringify(data,null,2)+'</pre>' );
}