简体   繁体   中英

Backbone.js toJSON() not including attributes

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM