Skip to content

Instantly share code, notes, and snippets.

@mikeando
Created June 2, 2011 03:14
Show Gist options
  • Save mikeando/1003862 to your computer and use it in GitHub Desktop.
Save mikeando/1003862 to your computer and use it in GitHub Desktop.
Javascript data bindings using closures
<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>
$(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>' );
}
name: Javascript Closures for Data Binding
description: Example of how to use javascript closures to perform data binding. Uses jQuery to make things clear.
authors:
- Michael Anderson
resources:
- http://http://therobotsbrain.blogspot.com/
normalize_css: no
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment