2014-12-05 68 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