Backbone.js - 模型的属性未正确传递给视图

时间:2015-06-19 21:13:56

标签: backbone.js

我对骨干很新,并试图理解为什么" title"没有传递给正确的视图和打印。如果我使用title属性创建模型,它将传递给视图并打印正常。任何指针都将非常感激。

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();
});

1 个答案:

答案 0 :(得分:0)

好的,你实际上是在问几件事,让我们从上到下使用你的代码回答。

  1. 打印不正确

    success: function(response) {
        console.log("successfully fetched : "+ response.attributes); 
    }
    
  2. 成功回调实际上需要很少的参数,模型,响应和选项。我怀疑第一个参数可能希望是{responseText:“works”}等响应,第二个参数是实际模型。可以肯定的是,您只需记录响应即可查看返回的内容。

    1. console.log(appointment.attributes)应该打印出undefined,因为之前调用的fetch()是异步的,这意味着这行在fetch()之后执行,它没有等待fetch方法到完。

    2. 约会视图打印为空标题。此视图已初始化并且调用了render()。但没有任何保证,这项任命是正确的。快速修复是在fetch成功回调中执行render函数。像这样:

      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();
          }
      });