我使用单独的加载视图来处理加载 gif,该 gif 侦听我从模型/集合获取结果中触发的相关事件。负责渲染的视图在不关心加载 gif 的情况下这样做。加载 gif 基本上掩盖了在加载 gif 被删除时“显示”的结果:
var MyView = Backbone.View.extend({
initialize: function () {
this.listenTo(this.collection, 'reset', this.render);
},
render: function () {
// do whatever you need to here
}
});
var LoadingView = Backbone.View.extend({
el: '#loading',
initialize: function () {
this.listenTo(this.collection, 'fetchStarted', this.showLoader);
this.listenTo(this.collection, 'fetchFinished', this.hideLoader);
},
showLoader: function () {
var self = this;
if (this.waitHandle) {
clearTimeout(this.waitHandle);
delete this.waitHandle;
}
this.waitHandle = setTimeout(function () {
self.$el.removeClass('hide');
}, 300);
},
hideLoader: function () {
clearTimeout(this.waitHandle);
delete waitHandle;
this.$el.addClass('hide');
}
});
var MyCollection = Backbone.Collection.extend({
getResults: function () {
var self = this;
this.fetch({
beforeSend: function () {
self.trigger('fetchStarted');
},
complete: function () {
self.trigger('fetchFinished');
}
});
}
});
我使用加载视图中的超时来延迟显示加载 gif,以防它们不是必需的。