Backbone.js 获取模型并将其添加到集合

Backbone.js 获取模型并将其添加到集合,backbone.js,Backbone.js,toresolvelist.toJSON()不返回任何内容(而不是集合的对象) 我想这是一个等待集合被正确填充的问题,但我认为这是可以的,因为我在添加它之前等待模型获取成功 当我console.log(toresolvelist)时,它显示结果在这里。但是我不能通过.get或toJSON访问它,所以我猜console.log欺骗了我 我很难确定问题是什么,但我无法解决它 提前多谢 要获得模型的完整列表,需要等待每个XHR调用的解析。这可以在模型返回的值上完成。fetch: var RippleI

toresolvelist.toJSON()
不返回任何内容(而不是集合的对象)

我想这是一个等待集合被正确填充的问题,但我认为这是可以的,因为我在添加它之前等待模型获取成功

当我
console.log(toresolvelist)
时,它显示结果在这里。但是我不能通过
.get
toJSON
访问它,所以我猜
console.log
欺骗了我

我很难确定问题是什么,但我无法解决它


提前多谢

要获得模型的完整列表,需要等待每个XHR调用的解析。这可以在
模型返回的值上完成。fetch

var RippleId = Backbone.Model.extend({
    initialize: function(toresolve) {
        this.url= config.rippleaccount.id.urlModel+toresolve;
        this.set('id', toresolve)
    }
});

var RippleIds = Backbone.Collection.extend({
    model: RippleId,

    createIdList: function(toresolves) {
        var self = this;
        _.each(toresolves, function(toresolve) {

            var model = new RippleId(toresolve);
            model.fetch({
                success: function(model,response) {
                    self.add(model);
                }
            });

        });
    }
});

var toresolvelist = new rippleids();    
toresolvelist.createIdList(toresolves);

还有一个演示

和/或感谢您深入了解这一点。事实上,我理解这个问题,但仍然无法正确解决它=/var toresolvelist=新的RippleId();toresolvelist.createIdList(toresolves);问题是我想从外部var toresolvelist=new-rippleids()访问我的集合;toresolvelist.createIdList(toresolves);toresolvelist.get(“someid”)或toresolvelist.toJSON无法从外部工作我如何确保我的集合已准备就绪?再次感谢!在回调之外?你不能,操作的异步性质意味着你必须等待,不知何故,回迁已经通过承诺或事件完成。好的,但是一旦我的集合被实例化,我如何以及何时才能访问模型?mycollection.get(“模型”);不起作用。我必须重写集合获取程序吗?
var RippleIds = Backbone.Collection.extend({
    model: RippleId,

    createIdList: function(toresolves) {
        var self = this, xhrs = [];

        xhrs = _.map(toresolves, function(toresolve) {
            var model = new RippleId(toresolve);
            var xhr = model.fetch().then(function() {
                self.add(model);
            });
            return xhr;
        });

        // promise that will resolve when all fetches have completed
        var combined = $.when.apply(null, xhrs);

        // event triggered when all models have been instantiated
        combined.then(function() {
            self.trigger('allin');
        });

        return combined;
    }
});

var toresolvelist = new rippleids();    
var promise = toresolvelist.createIdList(toresolves);

// with an event
toresolvelist.on('allin', function() {
    console.log('get model with an event', toresolvelist.get(1));
});

// with a promise
promise.then(function() {
    console.log(toresolvelist.toJSON());
});