Manage and observe state changes in JavaScript, based on Clojure(Script) atoms.
var atom = require('atom');
var gabriel = atom({likes: "ice cream"});
gabriel.addWatch("logger", function(state) {
console.log(state);
});
gabriel.state // => {likes: "ice cream"}
gabriel.swap(function(state) {
return {likes: "cookies"};
});
// {likes: "cookies"} will be logged in the console
gabriel.state // => {likes: "cookies"}
I want a clear distinction between state and identity.
Creates a new atom with initial state
.
Returns the current state for the atom a
.
Sets the state of atom a
to state
.
Sets the state of atom a
to the result of applying the function f
to the current state, a.state
, and the provided args
.
function setLike(state, food) {
return Object.assign({}, state, {likes: food});
}
a.swap(setLike, "hamburguers");
a.state.likes // => "hamburguers"
Like reset
but it will pass the metadata meta
to the watches.
Like swap
but it will pass the metadata meta
to the watches.
Invoke the function f
every time the state of the atom a
is
updated. The key
parameter is a String that is used to identify
the watch and remove it later.
Every time the function f
is invoked, it will recieve the following
params:
state
: current state of the atom, after the update.oldState
: the previous state of the atom, before the update. It is possible thatstate === oldState
if you don't update the atom's state or if you update the state in place. The functionf
is called every time one of the update methods are called, there is no guarantee that thestate
has actually changed and that the changes are preserved inoldState
. That is up to you.key
: the key provided when adding the watch.meta
: the metadata provided when performing the update withmreset
ormswap
. If the update was done throughreset
orswap
this parameter will beundefined
.
Stop invoking the function for the watch with the key
key.