获取并向集合添加模型

时间:2014-12-05 14:40:04

标签: backbone.js

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

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

我想这是一个等待集合已正确填充的问题,但我认为它没问题,因为我等待模型获取成功后再添加它。

当我console.log(toresolvelist)时,它告诉我结果在这里。但是我无法通过.gettoJSON访问它,所以我猜console.log正在欺骗我。

我很难确定问题所在并且我无法解决问题。

提前多多感谢!

1 个答案:

答案 0 :(得分:1)

要获得完整的模型列表,您需要等待每个XHR调用解析。对于model.fetch

返回的值,可以使用jquery.when来完成此操作
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());
});

演示http://jsfiddle.net/nikoshr/13mz3r3y/4/