1

我已经用这个结束了我的精神束缚......

我正在尝试将包含模型对象属性的视图呈现到屏幕上。我能够让 html 呈现,但模型属性没有按预期插入到 div 中,而是呈现为undefined

让这如此令人沮丧的是,当我将视图对象记录到控制台时,我能够检查它并看到正确的模型与它相关联,并且用户的属性确实通过this > model > attributes存在。但是,如果尝试直接在我的代码中访问属性,然后将其记录到控制台,我会得到undefined

路由器显示动作

show: function(customer_id){
      var customer = new backbone_data.Models.Customer({id: customer_id});
      customer.fetch();
      var customerView = new backbone_data.Views.CustomerView({model: customer});   
      $("#app_container").append(customerView.render().el);
}

视图类中的渲染函数——这两个都不起作用

render: function(){
        this.$el.html("<h3>Hello, my age is "+this.model.get('age')+"</h3>");
        return this;
}

template: _.template("<h3>Hello, my age is <%= age %></h3>"),
render: function(){
        this.$el.html(this.template(this.model.attributes));
        return this;
}

显示对象属性的控制台图像 我从视图的渲染函数内部记录这些属性,如下所示:

render: function(){
        console.log(this);
        console.log(this.model.attributes.age);
        this.$el.html("<h3>Hello, my age is "+this.model.get('age')+"</h3>");
        return this;
}

您可以从屏幕截图中看到,虽然在控制台中记录视图对象时可以访问年龄属性,但在我的代码中直接记录它并在视图中呈现为未定义时,它是未定义的。

http://imgur.com/P453dKL

谢谢您的帮助!!!!!!!

4

1 回答 1

4

customer.fetch()执行异步请求以填充模型的数据。您的代码创建视图并在您之后立即将模型传递给它fetch()。试试这个:

customer.fetch({
    success: function(data)
    {
        var customerView = new backbone_data.Views.CustomerView({model: data});   
        $("#app_container").append(customerView.render().el);
    }
});

那应该等到fetch()完成并确保已检索到您想要的数据。

于 2013-09-18T17:42:14.160 回答