Search code examples
backbone.js

Backbone.js - Model's attribute is not getting passed to view correctly


I am very new to backbone and trying to understand why "title" is not getting passed to view and printing correctly. If I create model with title properties it passes to view and prints fine. Any pointer will be greatly appreciated.

HTML:

$(document).ready(function(){
//Model
var Appointment = Backbone.Model.extend({
    urlRoot : '/services/backbone'  // returns **{"title":"Ms. Kitty Hairball Treatment","cancelled":"false","id":"1"}**

});
var appointment = new Appointment();

appointment.fetch({

    success: function(response) {
        console.log("successfully fetched : "+ response.attributes); // **prints undefine**
    }
});

console.log(appointment.attributes);

var AppointmentView = Backbone.View.extend({
  render: function(){

    $(this.el).html(this.model.get("title")); // **prints empty**
    return this;
  }
});


//console.log(JSON.stringify(appointment.attributes));
//// Initialize view with model
var appointmentView = new AppointmentView({el: "#app-test", model: appointment});

appointmentView.render();
});

Solution

  • Ok, you are actually asking few things, let's answer using your code from top to bottom.

    1. Not print properly

      success: function(response) {
          console.log("successfully fetched : "+ response.attributes); 
      }
      

    The success callback actually takes few parameters, a model, a response and options. I suspect that the first argument probably expect to be a response like {responseText:"works"} etc, and second argument is the actual model. To be sure, you could just log the response to see what was returned.

    1. console.log(appointment.attributes) should print out undefined because the fetch() that was called earlier is asynchronous, meaning this line is executed right after fetch(), it did not wait for the fetch method to finish.

    2. The Appointment View prints empty for what should be title. This View was initialed and render() was called. But there is no guanrantee that the appointment is fetched correctly. A quick fix would be the execute the render function inside the fetch success callback. like this:

      var Appointment = Backbone.Model.extend({
          urlRoot : '/services/backbone'  // returns **{"title":"Ms. Kitty Hairball Treatment","cancelled":"false","id":"1"}**
      });
      var AppointmentView = Backbone.View.extend({
          render: function(){
              $(this.el).html(this.model.get("title")); 
              return this;
          }
      });
      var appointment = new Appointment();
      var appointmentView = new AppointmentView({el: "#app-test", model: appointment});
      appointment.fetch({
          success: function(response) {
              appointmentView.render();
          }
      });