2012-08-10 60 views
8

我一直在使用木偶一個禮拜,它真的讓我的生活更輕鬆!觸發器加載視圖收集或模型獲取

現在我需要能夠在獲取集合或模型時通知用戶,因爲某些視圖需要大量時間來呈現/獲取。舉個例子,我做了一個小樣機:

http://i.stack.imgur.com/IU3BP.png

當用戶點擊某個類別,需要加載該類別中的所有項目的集合。在獲取集合之前,我想顯示一個加載視圖,如圖中所示(視圖1)。什麼將是一個優雅的解決方案來實現這一點。我發現以下帖子中用戶啓用了獲取觸發器:http://tbranyen.com/post/how-to-indicate-backbone-fetch-progress。這似乎工作,但不是我想要的。這是我想出了:

var ItemThumbCollectionView = Backbone.Marionette.CollectionView.extend({ 
     collection: new ItemsCollection(userId), 
     itemView: ItemThumbView, 
     initialize: function(){ 
      this.collection.on("fetch", function() { 
       //show loading view 
      }, this); 
      this.collection.on("reset", function() { 
       //show final view 
      }, this); 
      this.collection.fetch(); 

      Backbone.history.navigate('user/'+identifier); 
      this.bindTo(this.collection, "reset", this.render, this) 
     } 
    }); 

這將是很好,雖然如果我能有一個叫「LoadItemView」例如可選屬性。在抓取過程中會覆蓋itemView。你認爲這會是一個很好的做法嗎?

+0

使用collection.on('request')而不是collection.on('fetch')。和collection.fetch({reset:true})而不是collection.fetch()。 ;) – 2013-12-05 08:41:03

回答

1
+2

雖然這個解決方案存在問題。如果您的抓取返回零項,「加載」屏幕將永遠不會消失。 – 2012-08-10 21:31:22

+0

我認爲Boedy的想法是正確的。儘管我肯定會使用'this.bindTo(collection'而不是'this.collection.on'),我可能把這個邏輯放在一個單獨的對象中,而不是直接放在視圖中,但我認爲這個想法很好。 – 2012-08-10 21:32:19

+0

謝謝,現在emptyView對我有用,我想我可以在返回一個空集合的時候觸發一個事件 – Boedy 2012-08-10 22:43:43

0
var myCollection = Backbone.Marionette.CollectionView.extend({ 
    initialize: function(){ 
     this.collection.on('request', function() { 
      //show loading here 
     }) 
     this.collection.on('reset', function() { 
      //hide loading here 
     }) 
     this.collection.fetch({reset: true}) 
    } 
}) 

現在好多了,我想。

0

使用骨幹同步方法

/*超過騎乘同步應用程序的每個請求來聽到除了直接AJAX的*/

Backbone._sync = Backbone.sync; 
Backbone.sync = function(method, model, options) { 
    // Clone the all options 
    var params = _.clone(options); 

params.success = function(model) { 
    // Write code to hide the loading symbol 
    //$("#loading").hide(); 
    if (options.success) 
     options.success(model); 
}; 
params.failure = function(model) { 
    // Write code to hide the loading symbol 
    //$("#loading").hide(); 
    if (options.failure) 
     options.failure(model); 
}; 
params.error = function(xhr, errText) { 
    // Write code to hide the loading symbol 
    //$("#loading").hide(); 
    if (options.error) 
     options.error(xhr, errText); 
}; 
// Write code to show the loading symbol 
    //$("#loading").show(); 
Backbone._sync(method, model, params); 

};

0

一般來說,我會建議在讀取數據時加載預加載器,然後顯示集合。例如:

region.show(myPreloader); 
collection.fetch().done(function() { 
    region.show(new MyCollectionView({ collection: collection }); 
});