在與Backfire的模型相當廣泛的工作後,我對此有幾點想法。我希望他們中的一些人能爲你的項目提供很好的創意。
改變心智模式實時環境
首先,走出知道什麼時候「中的所有數據被加載」的心態,假設這麻煩你了,因爲它沒有我早期。我們現在處於實時環境中。從零開始,將每個記錄作爲更新處理。這樣可以節省很多時間和精力來處理狀態。
懶惰的渲染和DOM綁定
現在有了骨幹,我經常發現自己想要做一個懶惰的渲染。也就是說,我要處理以下條件邏輯:
- 開始收集數據,立即,但沒有表現出來,直到渲染叫
- 顯示「加載」消息,直到一些數據出現
- 當幾個記錄一起到達接近,不要再渲染每一個
一個很好的解決方案經常變化的數據是Backbone.ModelBinder的CollectionBinder tool,其操縱DOM的每個節點分別而不是重新繪製所有記錄。他們的網站上有很多例子,所以我不會在這裏詳細介紹。
防抖動作爲一個快速和骯髒的解決方案
下劃線的debounce方法是不需要數據綁定的所有複雜性較小規模的DOM操作的最佳解決方案。等待約250的反彈對我來說效果很好,確保渲染始終發生在數據更改上,但如果我們連續獲得大量更新,則只會出現一次。
假設我們已經創建了一個擴展Backbone.Firebase.Collection集合,然後我們可以做類似如下:
var View = Backbone.View.extend({
initialize: function() {
this.listenTo(this.collection, 'add remove', _.debounce(_.bind(this.dataChanged, this), 250));
},
render: function() {
this._isRendered = true;
/* do all my rendering magic here */
},
dataChanged: function() {
// wait until render has been called at least once
// if so, re-render on any change
this._isRendered && this.render();
}
});
使用延遲等待加載的數據
在我實施Backfire,我添加了一個有狀態的方法,通知我第一次加載。我使用jQuery的Deferred對象做了這個。然後,我只是聽收集到火sync
事件:
this.collection.once('sync', /* data is loaded */);
約火力地堡一個好處是,初始Firebase.on(「child_added」 ...)結果(現有記錄)往往進來一個又一個漂亮的大團。所以作爲一個額外的好處,我使用去抖動來使我的「加載」方法在初始叢塊完成後觸發,所以我沒有得到一條記錄,調用加載,然後立即需要採取一些行動來進行一系列更新。
由於這是實現特定的,我將是一個有點抽象這裏,但是這是它的要點:
// inside my wrapper for Backbone.Firebase.Collection
this.ready = $.Deferred();
// debounce our ready listener so it fires on the tail end of
// the initial update clump which reduces the number of update
// calls on the initial load process considerably
this.readyFn = _.debounce(this.ready.resolve, 250);
// start monitoring for the first series of updates
// this would need to be invoked before the sync is established
this.on('add', this.readyFn);
// wait for the data to come in
this.ready.always(_.bind(function() {
// when the ready promise is fulfilled, we can turn off the listener
this.off('add', this.readyFn);
// this is where we trigger the listener event used above
this.trigger('sync');
}, this));
我會用這個解決方案與服務。我發現,在大多數情況下,我可以通過忘記初始加載並將所有內容初始化爲空來將事情簡化,然後將所有內容都視爲更新。
我只在需要顯示一些替代視圖(如果沒有數據存在的情況下)(如入門指導)時才使用此功能。
我認爲正確的答案取決於你正在嘗試做什麼。加藤對你的各種選擇有很好的分析。你能分享一下爲什麼你想知道數據何時加載(而不是簡單地渲染對象,因爲你收到'添加'事件的集合)? – Anant 2013-03-07 16:49:57
我從項目列表中選擇一個隨機項目。我需要知道列表何時可用... – sprugman 2013-03-07 16:55:21
(該列表不會頻繁更改。) – sprugman 2013-03-07 17:02:18