Skip to content

Instantly share code, notes, and snippets.

@ngauthier
Last active December 20, 2015 00:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ngauthier/6039445 to your computer and use it in GitHub Desktop.
Save ngauthier/6039445 to your computer and use it in GitHub Desktop.
Backbone Scaffold
<!doctype html>
<html>
<head>
<title>Backbone Scaffold</title>
<script src="http://code.jquery.com/jquery-2.0.3.js"></script>
<script src="http://underscorejs.org/underscore.js"></script>
<script src="http://backbonejs.org/backbone.js"></script>
<script>
$(function() {
var Things = Backbone.Collection.extend({})
var ThingView = Backbone.View.extend({
tagName: "li",
render: function() {
this.$el.html(this.model.get("name"))
return this
}
})
var ThingsView = Backbone.View.extend({
tagName: "ol",
initialize: function() {
this.listenTo(things, 'all', this.render)
},
render: function() {
this.$el.empty()
things.each(function(thing){
var thingView = new ThingView({model: thing})
this.$el.append(thingView.render().el)
}, this)
return this
}
})
var NewThingView = Backbone.View.extend({
tagName: "form",
events: {
"submit": "addThing"
},
render: function() {
this.$el.html("<input name='name' placeholder='new thing'>")
return this
},
addThing: function(event) {
event.preventDefault()
var $input = this.$el.find("input")
things.add({
name: $input.val()
})
$input.val("")
}
})
var things = new Things();
var thingsView = new ThingsView()
$("#things").append(thingsView.render().el)
var newThingView = new NewThingView()
$("#things").append(newThingView.render().el)
})
</script>
</head>
<body>
<h1>Things</h1>
<div id="things"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment