Skip to content

Instantly share code, notes, and snippets.

@mikeymckay
Created June 13, 2011 21:07
Show Gist options
  • Save mikeymckay/1023706 to your computer and use it in GitHub Desktop.
Save mikeymckay/1023706 to your computer and use it in GitHub Desktop.
Form renderer
<html>
<head>
<script id="form-template" type="text/x-handlebars-template">
{{#formElements}}
<tr>
<td>
<label for='{{id}}'>{{label}}</label>
</td>
<td>
<input {{options}} id='{{id}}' type='{{type}}'></input>
</td>
</tr>
{{/formElements}}
</script>
</head>
<body>
<form>
<table id='form-elements'>
</table>
</form>
</body>
<script type="text/javascript" src="jquery-1.5.min.js"></script>
<script type="text/javascript" src="handlebars.js"></script>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="backbone.js"></script>
<script type="text/javascript">
var Form = Backbone.Model.extend({
});
var formTemplate = Handlebars.compile($("#form-template").html());
var FormView = Backbone.View.extend({
initialize: function (){
_.bindAll(this,'render');
this.model.bind('change', this.render);
this.model.view = this;
this.render();
},
el: $("form-elements"),
render: function(){
$("#form-elements").html(formTemplate(this.model.toJSON()));
}
});
var form = new Form();
form.set({
"formElements": [
{
"id": "A4X",
"label": "First Name",
"options": "data-optional='true'",
"type": "text"
}, {
"id": "G4R",
"label": "Last Name",
"options": "data-optional='false'",
"type": "text"
}, {
"id": "LP3",
"label": "Age",
"options": "data-absolute-max='130' data-absolute-min='0' data-max='95'",
"type": "number"
}
]
});
new FormView({
model: form
});
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment