Created
June 2, 2011 03:14
-
-
Save mikeando/1003862 to your computer and use it in GitHub Desktop.
Javascript data bindings using closures
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
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
<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> |
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
$(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>' ); | |
} |
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
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