Created
November 10, 2011 17:26
-
-
Save steveburkett/1355492 to your computer and use it in GitHub Desktop.
easy backbone
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> | |
<title>Drink menu</title> | |
</head> | |
<body> | |
<button id="add-drink">Add drink</button> | |
<ul id="drinks-list"> | |
</ul> | |
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> | |
<script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script> | |
<script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script> | |
<script> | |
(function ($) { | |
Drink = Backbone.Model.extend({ | |
//Create a model to hold drink atribute | |
name: null | |
}); | |
Drinks = Backbone.Collection.extend({ | |
//This is our Drinks collection and holds our Drinks models | |
initialize: function (models, options) { | |
this.bind("add", options.view.addDrinks); | |
//Listen for new additions to the collection and call a view function if so | |
} | |
}); | |
AppView = Backbone.View.extend({ | |
el: $("body"), | |
initialize: function () { | |
this.drinks = new Drinks( null, { view: this }); | |
//Create a drinks collection when the view is initialized. | |
//Pass it a reference to this view to create a connection between the two | |
}, | |
events: { | |
"click #add-drink": "showPrompt", | |
}, | |
showPrompt: function () { | |
var drink_name = prompt("What is your favorite drink?"); | |
var drink_model = new Drink({ name: drink_name }); | |
//Add a new friend model to our Drink collection | |
this.drinks.add( drink_model ); | |
}, | |
addDrinks: function (model) { | |
//The parameter passed is a reference to the model that was added | |
$("#drinks-list").append("<li>" + model.get('name') + "</li>"); | |
//Use .get to receive attributes of the model | |
} | |
}); | |
var appview = new AppView; | |
})(jQuery); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment