backbone.js - Add model to collection after fetching it -


im having trouble figuring out how populate model's attributes server , add populated model collection , have collection rendered view. here's code have:

var moviedetails = new cinephile.models.moviedetailsmodel({ id: movie.get('id') }); this.collection.add(moviedetails); 

inside of moviedetailsmodel:

cinephile.models.moviedetailsmodel = backbone.model.extend({      url: function()     {         return '/cinephile/api/index.php?action=getmoviedetails&movieid=' + this.id;     },      initialize: function()     {         this.fetch();     } }); 

and this.collection collection model set cinephile.models.moviedetailsmodel

i listening items added collection , when are, following executed:

displaymovie: function(movie) {     var view = new cinephile.views.movieview({         model: movie,         classname: 'movie clearfix',         template: jst['app/scripts/templates/movieview.ejs'],     });      this.$("#my-movies").append(view.el); }, 

movieview looks this:

cinephile.views.movieview = backbone.view.extend({      initialize: function(options)     {         this.template = options.template;         this.render();     },      render : function()     {         this.$el.html(this.template(this.model.attributes));         return this;         }, }); 

the problem have template i'm using trying access attribute of model undefined. im pretty sure it's undefined because movedetailsmodel hasn't finished fetching before model added collection , subsequently rendered view.

how can solve issue? i'd able create moviedetailsmodel takes in id, use id movie details server , add populated model collection , render collection screen.

any appreciated.

backbone fetch returns jqxhr object, deferred objects promise. when fetch called, attributes not populated yet. promise objects have don ejqxhr function, callback can passed executed once request done.

i recommend moving fetch method not constructor, because there can return jqxhr object , access done function. here example:

var moviedetails = new cinephile.models.moviedetailsmodel({ id: movie.get('id') }); var promise = moviedetails.fetch(); promise.done(function() {     var view = new cinephile.views.movieview({model: moviedetails});     view.render(); }); 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -