Backbone.js toJSON() not including attributes

折月煮酒 提交于 2020-01-15 11:44:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!