Commit 9aa96182 authored by Kuo Jen Wei's avatar Kuo Jen Wei Committed by Commit Bot

[CCA] Add observer pattern to cca.state.

Bug: None
Test: By instrumented test code.
Change-Id: I7af7ada02e2a2bf09a7f174af03dd8c29e46c85e
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1775686
Commit-Queue: Kuo Jen Wei <inker@chromium.org>
Reviewed-by: default avatarShik Chen <shik@chromium.org>
Auto-Submit: Kuo Jen Wei <inker@chromium.org>
Cr-Commit-Position: refs/heads/master@{#691904}
parent e916e04f
......@@ -14,6 +14,42 @@ var cca = cca || {};
*/
cca.state = cca.state || {};
/**
* @type {!Map<string, Set<!function(boolean)>>}
* @private
*/
cca.state.observers_ = new Map();
/**
* Adds observer function to be called on any state change.
* @param {string} state State to be observed.
* @param {!function(boolean)} observer Observer function called with newly
* changed value.
*/
cca.state.addObserver = function(state, observer) {
let observers = cca.state.observers_.get(state);
if (observers === undefined) {
observers = new Set();
cca.state.observers_.set(state, observers);
}
observers.add(observer);
};
/**
* Removes observer function to be called on state change.
* @param {string} state State to remove observer from.
* @param {!function(boolean)} observer Observer function to be removed.
* @return {boolean} Whether the observer is in the set and is removed
* successfully or not.
*/
cca.state.removeObserver = function(state, observer) {
const observers = cca.state.observers_.get(state);
if (observers === undefined) {
return false;
}
return observers.delete(observer);
};
/**
* Checks if the specified state exists.
* @param {string} state State to be checked.
......@@ -29,5 +65,11 @@ cca.state.get = function(state) {
* @param {boolean} val True to set the state on, false otherwise.
*/
cca.state.set = function(state, val) {
const oldVal = cca.state.get(state);
if (oldVal == val) {
return;
}
document.body.classList.toggle(state, val);
const observers = cca.state.observers_.get(state) || [];
observers.forEach((f) => f(val));
};
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment