触发器加载视图收集或模型获取

触发器加载视图收集或模型获取

问题描述:

我一直在使用木偶一个礼拜,它真的让我的生活更轻松!触发器加载视图收集或模型获取

现在我需要能够在获取集合或模型时通知用户,因为某些视图需要大量时间来呈现/获取。举个例子,我做了一个小样机:

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

+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

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}) 
    } 
}) 

现在好多了,我想。

使用骨干同步方法

/*超过骑乘同步应用程序的每个请求来听到除了直接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); 

};

一般来说,我会建议在读取数据时加载预加载器,然后显示集合。例如:

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