2015-12-14 28 views
1

我想要實現的是PopUpView只會被調用 - 一旦所有的模型都被保存了。Jquery Promise Backbone Fetch

運行代碼時,彈出視圖在保存完成之前運行。

var promises = [] 
_.each(exampleModels, _.bind(function (resource) { 
    var filter = this.resources.get(resource.id); 
    filter.fetch(
      { 
       success: function (model, response) { 
        var participant = new Model({ 
         example: "text" 
        }); 
        promises.push(participant.save()); 
       } 
      }); 
}, this)); 

$.when.apply($, promises).then(_.bind(function() { 
    var popupForm = new PopUpView({ 

    }); 
    this.$el.append(popupForm.$el); 
}, this)); 

回答

1

問題是fetch也是異步的。所以當你點擊線$.when.apply(...時,promises是一個空的數組。所以由when返回的承諾直接觸發then

+0

感謝您的回答,你能告訴我如何做一個雙重的承諾,以適應上面的代碼? – Brent

+0

我會標記爲正確的,但如果你可以粘貼一個例子,我很樂意:) – Brent

1
  1. 您可以通過model.fetchmodel.save
  2. 利用deferred回報,您可以通過有thenreturn a new promise

你可以建立你的承諾的陣列這樣

變異諾言
var promises = _(ids).chain() 
    .map(function(id) { 
     // get the models you want 
     return c.get(id); 
    }) 
    .map(function(model) { // build a promise for each model 
     return model.fetch(). // promise returned by fetch 
      then(function(resp) { 
       var participant = new M({ 
        example: "text" 
       }); 
       return participant.save(); // promise returned by save 
      }); 
    }) 
    .value(); 

$.when.apply($, promises).then(function() { 
    console.log('done'); 
}); 

A第二演示http://jsfiddle.net/nikoshr/du44m1ha/

由於jQuery的1.8

+0

我不認爲這會在循環內使用它的上下文嗎? – Brent

+1

這將取決於循環,'_.map'基本上是一個更可讀的循環 – nikoshr