Once you have an existing cache, to modify the current value, you can utilize the .set()
method (defined on the object returned when initializing the cache).
Example Usage
For this example, we're using the cache that we defined here.
ui/components/player/index.js
import joystick from '@joystick.js/ui';
const Player = joystick.component({
events: {
'click .play': (event = {}, instance = {}) => {
window.player_state.set((state = {}) => {
return {
player: {
...(state || {}),
playing: true,
},
};
}, 'CHANGE_PLAYING_STATE');
},
'click .pause': (event = {}, instance = {}) => {
window.player_state.set((state = {}) => {
return {
player: {
...(state || {}),
playing: false,
},
};
}, 'CHANGE_PLAYING_STATE');
},
},
render: ({ props, state }) => {
return `
<div class="player">
<header>
<ul>
<li class="previous"><i class="mod-icon-skip-back"></i></li>
<li class="${props?.state?.playing ? 'pause' : 'play'}">
<i class="mod-icon-${props?.state?.playing ? 'pause' : 'play'}"></i>
</li>
<li class="next"><i class="mod-icon-skip-forward"></i></li>
</ul>
</header>
<footer>
<div class="progress-bar">
<div class="progress" style="width: ${(state?.player?.current_time / state?.player?.total_time) * 100}%;"></div>
</div>
</footer>
</div>
`;
},
});
export default Player;
To change the cache state, above, we reference player_state
on the window
and whenever we have a click on either our .play
or .pause
element, call to player_state.set()
to set the state. To the .set()
method, we pass a callback function that will be called automatically, passing the current state for us to modify. As a return value, we return the modified state object that will become the new current value.
As an example, we all pass a custom user_event_label
to .set()
which gives us a way to identify the change being made to the cache (beyond the built-in set
, change
, and unset
event types).
API
.set()
Definition
cache.set(callback: function, user_event_label: string) => void
Parameters
- callback function required
- A function that will be called passing the current state value, returning an updated version of the state value.
- user_event_label string
- A custom label for the change being made to the cache that's passed to the callback function to identify the change.
.set() callback
Definition
(current_state: any, internal_event_label: string, user_event_label: string) => object
Parameters
- current_state any
- The current value of the cache.
- internal_event_label string
- The generic, internal label used to describe the event taking place on the cache (e.g., set, change. or unset).
- user_event_label string
- A custom label for the change being made to the cache that's passed to the callback function to identify the change.