Created
July 27, 2015 20:39
-
-
Save aleroddepaz/6656561d62c1322c752b to your computer and use it in GitHub Desktop.
Backbone example with a Model, Collection and View
This file contains 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
(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); |
This file contains 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>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