问题
I really can't wrap my head around this one. For some reason, (and I suspect it has something to do with asynchronous requests) my model attribute is not being converted properly using the toJSON() function. FWIW, I'm attempting to do lazy loading with django-relational fetchRelated().
Here's where I made the fetchRelated() request and create a new view.
$.when(usermodel.fetchRelated("movies")).then(function(){
var newview = new UserMovieList({model: usermodel});
newview.render();
});
And this calls up the following render function:
render: function(){
$(this.el).html(this.template({}));
var usermodel = this.model;
var wrapper = $(".movies");
var recipes = usermodel.get("movies");
movies.each(function(movie){
var movie_item = new UserMovieListItem({
model:movie
});
movie_item.render();
wrapper.append(movie_item.el);
});
return this;
Which then calls the UserMovieListItem render function:
render: function(){
console.log("movies to JSONify", this.model.attributes);
console.log("movies JSONified", this.model.toJSON());
$(this.el).html(this.template(this.model.toJSON()));
return this;
Here's the kicker. The first console.log (this.model.attributes) displays all of the attributes as they should be. It seems perfectly fine. But (this.model.toJSON()) only returns the URI and id attributes which were provided before the fetchRelated(). What the heck is going on here? If I bind this.model in UserMovieListItem with 'change' to render, then it will render, but after half a second or so... },
My User model is defined as such:
window.User = Backbone.RelationalModel.extend({
urlRoot: '/movie/api/v1/users/',
relations: [{
type: Backbone.HasMany,
key: 'movies',
relatedModel: 'Movie',
collectionType: 'UserMovieCollection',
reverseRelation: {
key: 'user',
includeInJSON: 'id'
}
}],
select: function(){
var model = this;
model.set({selected: true});
}
});
回答1:
fetchRelated
returns array of jqXHR
objects, and you need to use it with $.when this way:
$.when.apply(null, usermodel.fetchRelated("movies")).then(function(){
var newview = new UserMovieList({model: usermodel});
newview.render();
});
来源:https://stackoverflow.com/questions/10749639/backbone-js-tojson-not-including-attributes