Pergunta

I am at the end of my mental leash with this one...

I am attempting to render a view to the screen that contains a model object attribute. I am able to get the html to render but the model attribute is not inserted into the div as expected but is instead rendering as undefined.

The thing that makes this so frustrating is that when I log the view object to the console I am able to inspect it and see that the correct model is associated with it and that the user's attributes are indeed present via this > model > attributes. However, if try to access the attributes directly in my code and then log that to the console I get undefined.

router show action

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 in view class -- both of these do not work

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

console image showing object attributes I am logging these from inside the view's render function like so:

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

You can see from the screenshot that while the age attribute is accessible when logging the view object in the console, it is undefined when logging it directly in my code and rendering as undefined in the view.

http://imgur.com/P453dKL

Thanks for the help!!!!!!!

Foi útil?

Solução

customer.fetch() performs an asynchronous request to populate the model's data. Your code creates the view and passes it the model immediately after you fetch(). Try this:

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

That should wait until the fetch() is completed and ensure that the data you want has been retrieved.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top