2011-08-22 90 views
2

在我的骨幹應用程序中加載3個集合,並在渲染函數中綁定「重置」事件。所以,通過這種方式,當我獲取集合時,我會打印各種結果,但不會同時打印。骨幹,在全部加載時觸發事件

我會使用jquery延遲方法($ .when,$ .then)同時打印所有,如何在視圖上使用「綁定事件」來執行此操作?

這是代碼:

路由器:

App.Routers.test1 = Backbone.Router.extend({ 

    routes: {  
     "/test" : "test"   
    }, 

    initialize: function() {        
     // Models 
     this.Models_1 =  new App.Collections.coll_1;  
     this.Models_2 =  new App.Collections.coll_2; 
     this.Models_3 =  new App.Collections.coll_3; 

     // Views 
     this.View_1 =  new App.Views.view_1({model: this.Models_1}); 
     this.View_2 =  new App.Views.view_2({model: this.Models_2}); 
     this.View_3 =  new App.Views.view_3({model: this.Models_3});   
    }, 

    test: function() { 
     $.when(

      this.Models_1.fetch(), 
      this.Models_2.fetch(), 
      this.Models_3.fetch() 

     ).then(function() { 

      // ????????????????????????? 

      // What should I do here? 

      // ????????????????????????? 

     }); 
    } 

}); 

視圖1:

App.Views.view_1 = Backbone.View.extend({ 

    initialize: function() { 
     _.bindAll(this, 'render'); 
     this.model.bind('reset', this.render); 
    }, 

    render: function() { 

     // print the data... 

    } 

}); 

回答

6
test: function() { 
    $.when(
     this.Models_1.fetch({silent: YES}), // silent will prevent triggering any events on reset or add 
     this.Models_2.fetch({silent: YES}), 
     this.Models_3.fetch({silent: YES}) 
    ).then(_.bind(function() { 
     this.Models_1.trigger('reset'); // manually trigger events in sequence you want 
     this.Models_3.trigger('reset'); 
     this.Models_2.trigger('reset'); 
    }, this)); 
} 
+0

在「then」功能中,「this」不起作用。怎麼做? – keepyourweb

+0

將綁定範圍的代碼更新爲'then'函數 –

1

不知道你在哪裏與你的延遲事件去。骨幹已經有辦法做到這一點。

在您的視圖中,將集合中的事件「refresh」綁定到視圖渲染函數。每當您調用集合上的提取操作時,都會觸發刷新事件並重新顯示您的視圖。

+1

在上一個骨幹版本中,事件「refresh」被替換爲「reset」。但是現在應用程序運行正常,但是當我在集合上調用fetch時,應用程序會等待所有集合都被加載,然後繼續渲染。這樣視圖將同時打印。 – keepyourweb

+0

啊,這是不明確的你的問題。我想你應該刪除綁定到重置事件,並創建一個新的「加載:完成」或類似的東西。在你的意見中傾聽它,然後在你的「觸發」中觸發它。 – Julien

0

也許下劃線defer是你正在尋找的方法?

推遲調用該函數,直到當前調用堆棧已被清除,類似於使用延遲爲0的setTimeout。用於在不阻止UI線程更新的情況下執行昂貴的計算或HTML呈現。