0

My code work in three step:

  • I fetch a collection with a structure.
  • I populate the collection.
  • I render the collection with collectionView.

When i render the collection with cssElementListView,

  • if i let alert("toto"), it render me properly all the collection.
  • If not, it just render me [Object object].

What's wrong ?

 /************************************ Collection *******************************/

var cssElementList = Backbone.Collection.extend({
//on permet de charger different model de donnée
    initialize: function(props) {
        var self=this;

    // binding definition
        _.bindAll(this, "populate");
        this.bind('reset', this.populate);

        // get value from props
        this.url=(props.url==undefined)? "model.json" : props.url;
        this.elem=(props.elem==undefined)? "#age" : props.elem;
        this.model=(props.model==undefined)? cssElement : props.model;
        this.meta("result", "false");

    //fetch with url JSON file
        this.fetch();
    },

    populate: function(){
        var self=this;
        this.each(function(model){
            var mid=model.get('id');
            var mavaleur=$(self.elem).css(mid);
            model.set("value",mavaleur);
        });
    },
});

/************************************ CollectionView *******************************/
//Collection View
var cssElementListView = Backbone.View.extend({
    initialize: function() {
        _.bindAll(this, 'render');
        this.render();
    },
    render: function(){
        var self=this;
        //TROUBLE IS HERE
        alert("toto");
        this.collection.each(function(model){
            var view = new cssElementView({ el: this.el, model: model });
            $(this.el).append(view.render());
        },this);
    }
});
4

1 回答 1

1

I suspect it is a problem with the asynchronous nature of fetch(). your call to alert gives it enough time to finish fetching the data from the server, but if you don't make the call, the collection is still empty when you try to render because the ajax for fetch hasn't returned from the server and called its success callback yet. (you can read through the code here, around line 758.)

You would be better off binding your render to a reset event (or other event) rather than rendering immediately when you initialize your view, like so:

// in cssElementListView.initialize 
this.collection.on('reset', this.render, this);    
于 2012-06-14T16:02:45.083 回答