copenndthagen
copenndthagen

Reputation: 50722

BackboneJS Issue with accessing model attribute

I have a BackboneJS view coded as below;

var MyView = BaseView.extend({
    initialize: function() {
        this.myModel = new myModel();
        this.myModel.url = "api/myRESTApi/";
        this.myModel.fetch();
    },
    render: function () {
        var self = this;

        var myPanel = new Panel({
            title       : "My Custom Panel component",
            id          : "my-panel",
        });

        myPanel.on("onRender", function() {
            self.myModel.get("myModelAttr").toJSON()
        }   
    }

}); 

Now the issue is inside myPanel.on("onRender")

I am unable to get

self.myModel.get("myModelAttr")

On debug, I see that the attributes for self.myModel are null.

This happens even though I get the response properly from the REST resource and I also parse and set the attributes correctly in my model.

Am I doing something wrong here ?

Upvotes: 1

Views: 37

Answers (1)

Ryank
Ryank

Reputation: 507

The likely hood is that the model hasn't populated yet by the fetch as it runs asynchronously, try wrapping the fetch with a success statement to then render.

var self = this;

this.myModel.fetch({
    success:function () {
        // do something here like self.render()
    }
});

This way the model has been updated! or you could listen on a attribute change event as follows in the initialize method:

this.listenTo(this.myModel, 'change', this.render);

Depending on the data you are attempting to get from the model you shouldn't need to use toJSON() at the end of your statement either unless rendering out to the template.

Upvotes: 1

Related Questions