2014-12-05 93 views
2
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正在欺骗我。

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

非常感谢!

+0

http://stackoverflow.com/questions/11459244/backbone-js-empty-array-attribute/11463190 #11463190和http://stackoverflow.com/questions/8413500/backbone-js-populating-a-collection/8415515#8415515或http://stackoverflow.com/questions/26781970/returning-a-backbone-collection-and - 通过不与一个视图/ 26782761#26782761 – nikoshr 2014-12-05 14:44:41

+0

谢谢深入了解 – 2014-12-05 14:50:57

+0

其实我理解这个问题,但仍然无法正确解决它; =/ – 2014-12-05 15:45:02

回答

1

要获得模型的完整列表,您需要等待每个XHR呼叫解决。这可以jquery.when上返回的值来完成通过model.fetch

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/

+0

var toresolvelist = new rippleids(); toresolvelist.createIdList(toresolves); – 2014-12-05 16:26:03

+0

问题是我想从外部访问我的收藏 var toresolvelist = new rippleids(); toresolvelist.createIdList(toresolves); toresolvelist.get(“someid”)或toresolvelist.toJSON不起作用 从外面我怎么能确定我的收藏已准备好?再次感谢! – 2014-12-05 16:32:35

+0

回调之外?你不能,操作的异步性质意味着你必须等待,不知何故,提取已经完成了承诺或事件。 – nikoshr 2014-12-05 16:35:20