Skip to content
Permalink
Newer
Older
100644 68 lines (56 sloc) 1.83 KB
1
define(["sugar-web/activity/activity", "sugar-web/env"], function (activity, env) {
November 19, 2013 14:06
3
'use strict';
4
5
// This is a helper module that allows to persist key/value data
6
// using the standard localStorage object.
7
//
8
// Usage:
9
// ------
10
//
11
// // 1. Setup:
12
//
13
// dictstore.init(onReadyCallback);
14
//
15
// // 2. Use localStorage directly, and then call save():
16
//
17
// var value = localStorage['key'];
18
// localStorage['key'] = newValue;
19
// dictstore.save(onSavedCallback);
20
//
21
var dictstore = {};
22
23
dictstore.init = function (callback) {
24
25
if (env.isStandalone()) {
26
// In standalone mode, use localStorage as is.
27
callback();
28
29
} else {
30
// In Sugar, set localStorage from the datastore.
31
localStorage.clear();
32
33
var onLoaded = function (error, metadata, jsonData) {
34
var data = JSON.parse(jsonData);
35
for (var i in data) {
36
localStorage[i] = data[i];
37
}
38
39
callback();
40
41
};
42
activity.getDatastoreObject().loadAsText(onLoaded);
43
}
44
};
45
46
// Internally, the key/values are stored as text in the Sugar
47
// datastore, using the JSON format.
48
dictstore.save = function (callback) {
49
if (callback === undefined) {
50
callback = function () {};
51
}
52
53
if (env.isStandalone()) {
54
// In standalone mode, use localStorage as is.
55
callback();
56
} else {
57
var datastoreObject = activity.getDatastoreObject();
58
var jsonData = JSON.stringify(localStorage);
59
datastoreObject.setDataAsText(jsonData);
60
datastoreObject.save(function (error) {
61
callback(error);
62
});
63
}
64
};
65
66
return dictstore;
67
68
});