1 // Copyright (c) 2013 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.
6 * @fileoverview Implementation of ScreenContext class: key-value storage for
7 * values that are shared between C++ and JS sides.
9 cr.define('login', function() {
10 function require(condition, message) {
16 function checkKeyIsValid(key) {
17 var keyType = typeof key;
18 require(keyType === 'string', 'Invalid type of key: "' + keyType + '".');
21 function checkValueIsValid(value) {
22 var valueType = typeof value;
23 require(['string', 'boolean', 'number'].indexOf(valueType) != -1,
24 'Invalid type of value: "' + valueType + '".');
27 function ScreenContext() {
32 ScreenContext.prototype = {
34 * Returns stored value for |key| or |defaultValue| if key not found in
35 * storage. Throws Error if key not found and |defaultValue| omitted.
37 get: function(key, defaultValue) {
39 if (this.hasKey(key)) {
40 return this.storage_[key];
41 } else if (typeof defaultValue !== 'undefined') {
44 throw Error('Key "' + key + '" not found.');
49 * Sets |value| for |key|. Returns true if call changes state of context,
52 set: function(key, value) {
54 checkValueIsValid(value);
55 if (this.hasKey(key) && this.storage_[key] === value)
57 this.changes_[key] = value;
58 this.storage_[key] = value;
62 hasKey: function(key) {
64 return this.storage_.hasOwnProperty(key);
67 hasChanges: function() {
68 return Object.keys(this.changes_).length > 0;
72 * Applies |changes| to context. Returns Array of changed keys' names.
74 applyChanges: function(changes) {
75 require(!this.hasChanges(), 'Context has changes.');
76 Object.keys(changes).forEach(function(key) {
78 checkValueIsValid(changes[key]);
79 this.storage_[key] = changes[key];
81 return Object.keys(changes);
85 * Returns changes made on context since previous call.
87 getChangesAndReset: function() {
88 var result = this.changes_;
95 ScreenContext: ScreenContext