Code School - Part 1http://www.codeschool.com/courses/anatomy-of-backbonejs1. Create a Model Classvar Appointment = Backbone.Model.extend({});2. Create a Model instancevar appointment = new Appointment();3. Set an Attributeappointment.set('title', 'My knee hurts');4. Create a View Class & Define Rendervar AppointmentView = Backbone.View.extend({render: function(){$(this.el).html('<li>' + this.model.get('title') + '</li>');}});5. Create a View Instancevar appointmentView = new AppointmentView({model: appointment});6. Render the View Instance and Insert it's top-level element into elementappointmentView.render();$('#app').html(appointmentView.el);5. Custom JSONCode School - Part 2http://www.codeschool.com/courses/anatomy-of-backbonejs-part-21. Parse non-standard JSONInstead 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 Namevar Appointment = Backbone.Model.extend({ parse: function(response){ response.appointment. cancelled = response.appointment. cankelled; delete response.appointment.cankelled; return response.appointment; } });3. Id Attributevar 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;
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)); } });
Wednesday, August 21, 2013
Learning Backbone.js
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment