Welcome to the Anatomy of Backbone.js challenges! We're going to be building a simple Appointment app for our friend, Dr. Goodparts.
So, let's get started and create an Appointment model
class.
var Appointment = Backbone.Model.extend({});
Now that we have our Appointment model class, let's create our first instance and assign it to the appointment
variable. Pass in a title for the appointment
when creating it.
Note Check out the JS Source tab below that will display relevant code for this challenge.
//Define a object for model var appointment = new Appointment({'title': "New appointment"});
Well look at that, we have our very first appointment. But it isn't so useful, sitting there deep down in the bowels of your browser. To display it lets first create a view
class and name it AppointmentView
.
//Create a View CLASS var AppointmentView = Backbone.View.extend({});
The perfect place to put our display code now exists! Now it's time to create our first AppointmentView instance. When doing so, don't forget to include the appointment model instance we just created. Assign the instance to a variable.
var appointmentView = new AppointmentView({model: appointment });
Our AppointmentView
instance is almost ready, all we have to do is go back and define the AppointmentViewrender
function so we can actually create some HTML. Have the render function add an <li>
tag to the top-level element of the view. Use this.model.get('title')
as the content of the <li>
.
var AppointmentView = Backbone.View.extend({ render: function(){ var html = '<li>'+this.model.get('title')+'</li>'; $(this.el).html(html); } });
Almost there, but before we display anything let's set
the title of the appointment
instance! Set it to any string, perhaps something you'd like Dr. Goodparts to take a look at (ex. My Backbone Hurts
).
appointment.set('title', "Nice to meet you!");
Time to show Dr. Goodparts his first appointment. Render the appointmentView
instance and then insert its top-level element into #app
using $('#app').html()
.
//Show the final view appointmentView.render(); $('#app').html(appointmentView.el);
-----Final code----
//Create a model CLASS var Appointment = Backbone.Model.extend({}); //Define a object for model var appointment = new Appointment({'title': "New appointment"}); //Create a View CLASS var AppointmentView = Backbone.View.extend({ render: function(){ var html = '<li>'+this.model.get('title')+'</li>'; $(this.el).html(html); } }); //create a view object, include the model instance var appointmentView = new AppointmentView({model: appointment }); //set title appointment.set('title', "Nice to meet you!"); //Show the final view appointmentView.render(); $('#app').html(appointmentView.el);