你說的是正確的道路,但主要是將數據存儲在JavaScript中。適當時將它與本地存儲器結合使用。
當我構建應用程序(如您所描述的應用程序)時,我通常會小心地設置通過API接收的數據的JavaScript表示。
一個這樣的表示可能看起來如下。請記住,我的示例代碼在下面做了一些假設。
- 它讓你有定義的
api
對象,它負責調用API的假設,並調用完成回調。
- API返回的數據是簡單地可以分配給JavaScript變量的JSON,
- 返回的JSON是一個對象列表,每個對象都有一個「id」字段。
- 你有某種事件對象,我通常會構建自己的自定義事件,基本上將對象作爲偵聽器,並在觸發時通過偵聽器並根據具體情況調用帶有或不帶有負載的函數。
數據容器,例如:
MYAPP.data.BaseContainer = function (api_url, loadedEvent) {
var self = {
// Array to store the data returned via the APIs
_data : [],
// The API URL used to fetch data
api_url : api_url,
// Boolean flag to signify whether the _data variable has been populated
is_loaded : false,
// The even to fire once _data has been populated
loadedEvent : loadedEvent,
/**
* Returns the state of the is_loaded variable
*/
loaded : function() {
return self.is_loaded;
},
/**
* Takes an ID and returns any member of the _data array
* that has that ID.
*
* @param id : an String or integer representing the ID.
* @returns {Object}
*/
byId : function (id) {
var toReturn = null;
for (var i = 0, len = self._data.length; i < len; i++) {
if (self._data[i].id == id) {
toReturn = self._data[i];
break;
}
}
return toReturn;
},
/**
* Returns the entire _data array.
*/
all : function() {
return self._data;
},
/**
* This simple callback just stores the json response in
* its entirety on the _data variable.
*/
callback : function(data) {
self._data = data;
self.is_loaded = true;
loadedEvent.fire(self._data);
},
/**
* Calls the API, if no callback has been specified as a parameter
* self.callback is used.
*/
getFromAPI : function(callback) {
if (typeof callback === 'undefined') {
callback = self.callback;
}
api.get(self.api_url, callback);
}
};
self.getFromAPI();
return self;
};
有了這個藍圖,我現在可以創建特定的數據容器是這樣的:
/**
* Stores a list of "friends" gotten from the API.
* This is basically an instance of the BaseContainer object defined above.
*/
MYAPP.data.Friends = (function() {
var self = MYAPP.data.BaseContainer("API_URL_TO_FECTH_FRIENDS_LIST", FriendsLoadedEvent);
return {
byId : self.byId,
all : self.all,
loaded : self.loaded
};
}());
由於作爲該代碼運行很快,一個API調用時,完成後將會觸發FriendsLoadedEvent
。所以,說穿了,我通常使用JavaScript來存儲我的東西。但是如果你想把LocalStorage放入混合中也很容易!
只需將本地存儲代碼添加到BaseContainer對象中,該對象首先檢測客戶端是否實際支持本地存儲,如果是,則鏡像本地存儲中的_data字段。這樣可以在會話之間快速保持經常使用的數據。使用隨時可用的JSON分析工具將數據從JSON轉換爲LocalStorage「文本」並返回。
請記住,您不能依賴LocalStorage作爲您的主數據結構,您不能保證客戶端支持它,即使它確實存在多少數據的上限是不同的瀏覽器。所以用它來存儲數據:
- 你希望獲得很多時候,
- ,你覺得應該只是在那裏,立即只要用戶登錄,
- ,並且不經常更改足以保證不斷刷新API調用。
爲什麼選擇投票? – 2012-02-16 18:05:01
我沒有投票給你 - 我甚至沒有解鎖這個功能。如果我不得不猜測,有人把你的答案誤解爲諷刺。 – Steve 2012-02-16 18:09:42