Skip to content

Instantly share code, notes, and snippets.

@marijer
Created November 17, 2013 18:15
Show Gist options
  • Save marijer/7516278 to your computer and use it in GitHub Desktop.
Save marijer/7516278 to your computer and use it in GitHub Desktop.
/* Code school Snippets - Backbone part 2 */
/* 1. More Models */
// parsing data that comes in differently - through parse function
var Appointment = Backbone.Model.extend({
parse: function(response){
return response.appointment;
}
});
// change attributes and set id
// "appointment": { "title": "Ms. Kitty Hairball Treatment", "cankelled": false, "identifier": 1 }
var Appointment = Backbone.Model.extend({
idAttribute: 'identifier',
parse: function(response){
var appointment = response.appointment;
appointment.cancelled = appointment.cankelled;
delete appointment.cankelled;
return appointment;
}
});
// force the parsing
var appointment = new Appointment(data, {parse: true});
// toJSON no longer works on templates
var AppointmentView = Backbone.View.extend({
template: _.template('<span>' +
'<%= title %></span>' +
'<a href="#">x</a>'),
render: function(){
this.$el.html(this.template(this.model.attributes));
return this;
}
});
/* 2. Collections */
// tels also about pagination but a bit unclear how to implement that yet
// Use Comparators to sort data
var TodoItems = Backbone.Collection.extend ({
comparator: ‘status’
});
// Comparator as function -- sort status in reverse order
var TodoItems = Backbone.Collection.extend ({
comparator: function(todo1, todo2) {
return todo1.get('status') < todo2.get('status');
}
});
// get length of items
var TodoItems = Backbone.Collection.extend ({
completedCount: function () {
return this.where({status: 'complete'}).length;
}
})
// fetch data using parameters -- creates url like /appointments?since=2013-01-01&per_page=10
var appointments = new Appointments();
appointments.fetch({data: {since: "2013-01-01", per_page: 10}});
/* 3. Router */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment