priyanka patel
priyanka patel

Reputation: 637

fetch specific attribute from model in backbone.js

i am fetching data using following code

 _.each(cardIds, function(id){        
                   var mdc = new MdlCard({cardId: parseInt(id)});                                
                  mdc.fetch({data:{cardId: parseInt(id)}});
                   cards.reset(mdc); 
               });

cardIds contains cardId for particular list. in my cardview

initialize: function(){           
           _.bindAll(this,'render');
           this.model.bind('change', this.render, this);
           this.model.bind('destroy', this.remove, this);
       },
       render: function() {              
           var res = {data: this.model.toJSON(),ccId: this.model.cid};           $(this.el).html(this.template(res));                                                      

           chkIds = this.model.get('checklists');
           return this;
       },

i am passing this card model to template. but it will fetch two object per one request first object contains default value which i am defining while creating card model and second from the db(which actually i want)

but when i am writing this line chkIds = this.model.get('checklists'); it will return nothing. pls help me to find problem in this code.

Upvotes: 0

Views: 1044

Answers (1)

timDunham
timDunham

Reputation: 3318

in short, fetch is asynchronous. So when you create the model at first, it hasn't fetched all the values from the server yet. Once they're done fetching, it will re-render your view with the updated values. My guess is that you're rendering the view after you create it. You might instead wait for the model change event to fire (after the fetch is done) and it will render once the fetch is complete.

Another suggestions based on what you posted (not to do necessarily with the problem you're seeing): You don't have to set the data attribute when calling fetch. The default implementation of Backbone.sync will do that for you so mdc.fetch({data:{cardId: parseInt(id)}}); should be mdc.fetch();

Hopefully that's helpful--if so pls mark as answered as @tkone suggested

Upvotes: 2

Related Questions