Wednesday, August 21, 2013

Learning Backbone.js


1. Create a Model Class
var Appointment = Backbone.Model.extend({});
2. Create a Model instance
var appointment = new Appointment();
3. Set an Attribute
appointment.set('title', 'My knee hurts');
4. Create a View Class & Define Render
var AppointmentView = Backbone.View.extend({
render: function(){
$(this.el).html('<li>' + this.model.get('title') + '</li>');
}
});
5. Create a View Instance
var appointmentView = new AppointmentView({model: appointment});
6. Render the View Instance and Insert it's top-level element into element
appointmentView.render();
$('#app').html(appointmentView.el);
Code School - Part 2
http://www.codeschool.com/courses/anatomy-of-backbonejs-part-2
1. Parse non-standard JSON
Instead of returning JSON like { "title": "Ms. Kitty Hairball Treatment", "cancelled": false, "id": 1 } the server is returning JSON like { "appointment": { "title": "Ms. Kitty Hairball Treatment", "cankelled": false, "identifier": 1 }
var Appointment = Backbone.Model.extend({ parse: function(response){ return response. appointment;
} });
2. Change Attribute Name
var Appointment = Backbone.Model.extend({ parse: function(response){ response.appointment. cancelled = response.appointment. cankelled; delete response.appointment.cankelled; return response.appointment; } });
3. Id Attribute
var Appointment = Backbone.Model.extend({ idAttribute: "identifier", parse: function(response){ var appointment = response.appointment; appointment.cancelled = appointment.cankelled; delete appointment.cankelled; return appointment; } });
4. Force Parse
var appointment = new Appointment(data, {parse:true}); appointment.attributes;
5. Custom JSON
var Appointment = Backbone.Model.extend({
  toJSON: function(){
    var attributes = _.clone(this.attributes);
    attributes.cankelled = attributes.cancelled;
    delete attributes.cancelled;
    return { appointment: attributes };
  }
});
6. Render Changes
var AppointmentView = Backbone.View.extend({ template: _.template('<span>' + '<%= title %></span>' + '<a href="#">x</a>'), render: function(){ this.$el.html(this.template(this.model.attributes)); } });

No comments:

Post a Comment