Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Backbone.js 主干集合foreach呈现与警报不同_Backbone.js - Fatal编程技术网

Backbone.js 主干集合foreach呈现与警报不同

Backbone.js 主干集合foreach呈现与警报不同,backbone.js,Backbone.js,我的代码分三步工作: 我获取一个具有结构的集合 我填充集合 我使用collectionView渲染集合 当我使用cssElementListView呈现集合时 如果我让alert(“toto”),它会正确地呈现我所有的收藏 如果没有,它只渲染我[Object] 怎么了 /************************************ Collection *******************************/ var cssElementList = Backbo

我的代码分三步工作:

  • 我获取一个具有结构的集合
  • 我填充集合
  • 我使用collectionView渲染集合
当我使用cssElementListView呈现集合时

  • 如果我让alert(“toto”),它会正确地呈现我所有的收藏
  • 如果没有,它只渲染我[Object]
怎么了

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

我怀疑这是fetch()的异步特性的问题。您对alert的调用为它提供了足够的时间来完成从服务器获取数据,但是如果您不进行调用,则在尝试呈现时集合仍然为空,因为用于获取的ajax尚未从服务器返回并调用其成功回调。(您可以阅读第758行附近的代码。)

最好将渲染绑定到重置事件(或),而不是在初始化视图时立即渲染,如下所示:

// in cssElementListView.initialize 
this.collection.on('reset', this.render, this);