Upstream version 11.40.271.0
[platform/framework/web/crosswalk.git] / src / ui / file_manager / audio_player / js / audio_player_model.js
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 (function(global) {
6   'use strict';
7
8   /**
9    * List of values to be stored into the model.
10    * @type {Object<string, *>}
11    * @const
12    */
13   var VALUES = Object.freeze({
14     shuffle: false,
15     repeat: false,
16     volume: 100,
17     expanded: false,
18   });
19
20   /**
21    * Prefix of the stored values in the storage.
22    * @type {string}
23    */
24   var STORAGE_PREFIX = 'audioplayer-';
25
26   /**
27    * Save the values in the model into the storage.
28    * @param {AudioPlayerModel} model The model.
29    */
30   function saveModel(model) {
31     var objectToBeSaved = {};
32     for (var key in VALUES) {
33       objectToBeSaved[STORAGE_PREFIX + key] = model[key];
34     }
35
36     chrome.storage.local.set(objectToBeSaved);
37   };
38
39   /**
40    * Load the values in the model from the storage.
41    * @param {AudioPlayerModel} model The model.
42    * @param {function()} callback Called when the load is completed.
43    */
44   function loadModel(model, callback) {
45     // Restores the values from the storage
46     var objectsToBeRead = Object.keys(VALUES).
47                           map(function(a) {
48                             return STORAGE_PREFIX + a;
49                           });
50
51     chrome.storage.local.get(objectsToBeRead, function(result) {
52       for (var key in result) {
53         // Strips the prefix.
54         model[key.substr(STORAGE_PREFIX.length)] = result[key];
55       }
56       callback();
57     }.bind(this));
58   };
59
60   /**
61    * The model class for audio player.
62    * @constructor
63    */
64   function AudioPlayerModel() {
65     // Initializes values.
66     for (var key in VALUES) {
67       this[key] = VALUES[key];
68     }
69     Object.seal(this);
70
71     // Restores the values from the storage
72     loadModel(this, function() {
73       // Installs observer to watch changes of the values.
74       var observer = new ObjectObserver(this);
75       observer.open(function(added, removed, changed, getOldValueFn) {
76         saveModel(this);
77       }.bind(this));
78     }.bind(this));
79   }
80
81   // Exports AudioPlayerModel class to the global.
82   global.AudioPlayerModel = AudioPlayerModel;
83
84 })(this || window);