Skip to content

Instantly share code, notes, and snippets.

@aleroddepaz
Created July 27, 2015 20:39
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 aleroddepaz/6656561d62c1322c752b to your computer and use it in GitHub Desktop.
Save aleroddepaz/6656561d62c1322c752b to your computer and use it in GitHub Desktop.
Backbone example with a Model, Collection and View
(function ($) {
// Create a model to hold friend atribute
Friend = Backbone.Model.extend({
name: null
});
// This is our Friends collection and holds our Friend models
Friends = Backbone.Collection.extend({
initialize: function (models, options) {
// Listen for new additions to the collection and call a view function if so
this.bind("add", options.view.addFriendLi);
}
});
AppView = Backbone.View.extend({
el: $("body"),
initialize: function () {
// Create a friends collection when the view is initialized
// Pass it a reference to this view to create a connection between the two
this.friends = new Friends(null, { view: this });
},
events: {
"click #add-friend": "showPrompt",
},
showPrompt: function () {
var friend_name = prompt("Who is your friend?");
var friend_model = new Friend({ name: friend_name });
// Add a new friend model to our friend collection
this.friends.add( friend_model );
},
addFriendLi: function (model) {
// The parameter passed is a reference to the model that was added
// Use .get to receive attributes of the model
$("#friends-list").append("<li>" + model.get('name') + "</li>");
}
});
var appview = new AppView();
})(jQuery);
<!doctype html>
<html>
<head><title>I have a back bone</title></head>
<body>
<button id="add-friend">Add Friend</button>
<ul id="friends-list"></ul>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.1/backbone-min.js"></script>
<script src="app.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment