Backbone App
HTML
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>
<button id="add-list">Click to Add Item</button>
<div id="selection">
<select id='select-list' name='select'>
<option>Select</option>
</select>
</div>
JavaScript
(function ($) {
//Create a model to hold friend atribute
Item = Backbone.Model.extend({
name: null
});
//This is our Friends collection and holds our Friend models
Items = Backbone.Collection.extend({
//Listen for new additions to the collection and call a view function if so
initialize: function (models, options) {
this.bind("add", options.view.addItemList);
}
});
AppView = Backbone.View.extend({
el: $("body"),
//Create a friends collection when the view is initialized.
//Pass it a reference to this view to create a connection between the two
initialize: function () {
this.friends = new Friends(null, {
view: this
});
},
events: {
"click #add-friend": "showPrompt",
},
//Add a new friend model to our friend collection
showPrompt: function () {
var friend_name = prompt("Who is your friend?"),
friend_model = new Friend({
name: friend_name
});
this.friends.add(friend_model);
},
addItemList: function (model) {
//The parameter passed is a reference to the model that was added
$("#select-list").append("<option>" + model.get('name') + "</option>");
//Use .get to receive attributes of the model
}
});
var appview = new AppView;
})(jQuery);