Created
April 28, 2012 22:05
-
-
Save finaiized/2522375 to your computer and use it in GitHub Desktop.
Simple example of using Backbone Model, Collection and Views in conjunction with Underscore templating.
This file contains hidden or 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() { | |
var Meal = Backbone.Model.extend({ | |
defaults: { | |
"appetizer": "Caesar Salad", | |
"entree": "Ravioli", | |
"dessert": "Cheesecake" | |
} | |
}); | |
var Meals = Backbone.Collection.extend({ | |
model: Meal | |
}); | |
var Menu = Backbone.View.extend({ | |
el: $('body'), | |
events: { | |
'click button#add': 'addMeal' | |
}, | |
template: _.template($("#template-menu").html()), | |
initialize: function() { | |
_.bindAll(this, 'render', 'addMeal'); | |
this.collection = new Meals(); | |
this.collection.add(new Meal()); | |
this.collection.add(new Meal({ | |
'appetizer': 'Poop' | |
})); | |
this.collection.bind('add', this.render); | |
this.render(); | |
}, | |
render: function() { | |
var html = this.template({ | |
meals: this.collection.toJSON() | |
}); | |
$('ol', this.el).html(html); | |
}, | |
addMeal: function() { | |
console.log("Added meal"); | |
this.collection.add(new Meal({'appetizer' : $('#appetizer').val() || "None"})); | |
} | |
}); | |
var menus = new Menu(); | |
}); |
This file contains hidden or 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<script src="jquery-1.7.2.min.js"></script> | |
<script src="underscore-min.js"></script> | |
<script src="backbone-min.js"></script> | |
<script src="json2.js"></script> | |
<script src="code.js"></script> | |
<meta charset=utf-8 /> | |
<title>JS Bin</title> | |
<!--[if IE]> | |
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> | |
<![endif]--> | |
<style> | |
article, aside, figure, footer, header, hgroup, menu, nav, section { | |
display: block; | |
} | |
</style> | |
</head> | |
<body> | |
<h1> Menu </h1> | |
<button id="add">Add meal</button> | |
<input type="text" id="appetizer"> | |
<ol> </ol > | |
<script type="text/html" id="template-menu"> | |
<% _.each(meals, function (meal) { %> <li> Appetizer: <%= meal.appetizer %> , | |
Entree: <%= meal.entree %> , | |
Dessert: <%= meal.dessert %> </li> | |
<% }); %> | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment