
模型(Model)和資料
|
57
Model.include({
toJSON: function(){
return(this.attributes());
}
});
現在再把 records 序列化成 JSON 字串,就能得到想要的正確結果:
var json = JSON.stringify(Asset.records);
json //= "{"7B2A9E8D...":"{"name":"document","ext":".txt","id":"7B2A9E8D..."}"}"
將物件序列化成 JSON 字串後,想再補上本地儲存區功能就簡單得多了。接下來,我們
會在
Model
裡新增兩個函式:
saveLocal()
和
loadLocal()
。當我們在儲存資料時,會把
Model.records
物件轉成陣列、序列化成 JSON 字串,最後傳進
localStorage
物件中:
var Model.LocalStorage = {
saveLocal: function(name){
// 將 records 轉換為陣列格式
var result = [];
for (var i in this.records)
result.push(this.records[i])
localStorage[name] = JSON.stringify(result);
},
loadLocal: function(name){
var result = JSON.parse(localStorage[name]); ...