forked from alexissan/ReactNativeWorkshop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FavoritesStore.js
68 lines (50 loc) · 1.3 KB
/
FavoritesStore.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
'use strict'
// We are using events emitter from nodejs:
// https://nodejs.org/api/events.html
var EventEmitter = require('events').EventEmitter;
var assign = require('object-assign');
var React = require('react-native');
var {
AsyncStorage
} = React;
var STORAGE_KEY = 'iTunesCatalog:Favorites';
var _favorites = {};
var FavoritesStore = assign({}, EventEmitter.prototype, {
CHANGE_EVENT: 'change',
loadPersistedFavorites() {
AsyncStorage.getItem(STORAGE_KEY)
.then((value) => {
if (value !== null) {
_favorites = JSON.parse(value);
this.emit(this.CHANGE_EVENT);
}
})
.done();
},
getAll() {
return Object.keys(_favorites).map(key => _favorites[key]);
},
isFavorite(album) {
return _favorites[album.collectionId] !== undefined;
},
toggleFavorite(album) {
if (this.isFavorite(album)) {
this.unfavorite(album);
} else {
this.favorite(album);
}
},
favorite(album) {
_favorites[album.collectionId] = album;
this.saveChanges();
},
unfavorite(album) {
delete _favorites[album.collectionId];
this.saveChanges();
},
saveChanges() {
AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(_favorites)).done();
this.emit(this.CHANGE_EVENT);
}
});
module.exports = FavoritesStore;