Skip to content

Instantly share code, notes, and snippets.

@brunogarcia
Last active December 15, 2015 12:48
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 brunogarcia/5262468 to your computer and use it in GitHub Desktop.
Save brunogarcia/5262468 to your computer and use it in GitHub Desktop.
A simple Backbone testing: model, collection, views, templates and router. Example based in Tuts+ Course: http://kcy.me/hml7
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>A simple Backbone testing</title>
</head>
<body>
<script id="userTemplate" type="text/template">
<li><%= id %></li>
<li><%= name %></li>
</script>
<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://backbonejs.org/backbone-min.js"></script>
<script src="backbone_testing.js"></script>
</body>
</html>
(function() {
window.App = {
Models: {},
Collections: {},
Views: {},
Router: {}
};
_.extend(window.App, Backbone.Events);
App.Models.User = Backbone.Model.extend({
defaults: {
id: null,
name: ""
}
});
App.Collections.Users = Backbone.Collection.extend({
model: App.Models.User
});
App.Views.Appointments = Backbone.View.extend({
el: $('body'),
initialize: function() {
//Listen if this event have been trigger
App.on('appointment:show', this.search, this);
},
search: function(id) {
return this.decide(this.collection.get(id), id);
},
decide: function(user, id) {
if (user === undefined)
this.error(id);
else
this.show(user);
},
show: function(user) {
var appointmentView = new App.Views.Appointment({model: user});
this.$el.html(appointmentView.el);
},
error : function(id) {
console.log("This id " + id + " does not exist");
}
});
App.Views.Appointment = Backbone.View.extend({
tagName: "ul",
template: _.template($('#userTemplate').html()),
initialize: function() {
this.render();
},
render: function(id) {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
App.Router = Backbone.Router.extend({
routes: {
'': 'index',
'appo/:id': 'showAppointment'
},
index: function() {
console.log( 'hi there from the index page' );
},
//Trigger an event to App
showAppointment: function(id) {
App.trigger('appointment:show', id);
}
});
var users = new App.Collections.Users(
[
{id: 1, name: "Eva"},
{id: 2, name: "Bruno"},
{id: 3, name: "Paco"},
]
);
new App.Views.Appointments({collection: users});
new App.Router;
Backbone.history.start();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment