Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <script src="https://rawgit.com/arqex/freezer/master/build/freezer.js"></script>
  <title>JS Bin</title>
</head>
<body>
</body>
</html>
 
// Let's create a freezer store
var freezer = new Freezer({
    a: {x: 1, y: 2, z: [0, 1, 2] },
    b: [ 5, 6, 7 , { m: 1, n: 2 } ],
    c: 'Hola',
    d: null // It is possible to store whatever
});
// Let's get the frozen data stored
var state = freezer.get();
// Listen to changes in the store
freezer.on('update', function( newValue ){
    // New value will have the updated store's data
    console.log( 'I was updated' );
});
// The data is read as usual
console.log( state.c ); // logs 'Hola'
// And used as usual
state.a.z.forEach( function( item ){
    console.log( item );
}); // logs 0, 1 and 2
// But it is immutable, so...
console.log('### Immutable');
state.d = 3; console.log( state.d ); // logs null
state.e = 4; console.log( state.e ); // logs undefined
// to update, use methods like set that returns new frozen data
var updated = state.set( 'e', 4 ); // On next tick it will log 'I was updated'
console.log('### Set');
console.log( state.e ); // Still logs undefined
console.log( updated.e ); // logs 4
// Store data has changed!
console.log(freezer.get() !== state); // true
console.log(freezer.get() === updated); // true
// The nodes that weren't updated are reused
console.log(state.a === updated.a); // true
console.log(state.b === updated.b); // true
// Updates can be chained because the new immutable
// data node is always returned
var updatedB = updated.b
    .push( 50 )
    .push( 100 )
    .shift()
    .set(0, 'Updated')
; // It will log 'I was updated' on next tick, just once
// updatedB is the current b property
console.log('### Chained');
console.log(freezer.get().b === updatedB); // true
// And it is different from the one that started
console.log(updated !== freezer.get()); // true
console.log(updated.b !== updatedB); // true
console.log( updated.b[0] ); // updated did't/can't change: logs 5
console.log( updatedB[0] ); // logs 'Updated'
console.log( updatedB[4] ); // logs 100
console.log(updatedB.length === 5); // true: We added 2 elements and removed 1
// Untouched nodes are still the same
console.log(state.a === freezer.get().a); // still true
console.log(updated.a === freezer.get().a); // still true
// Reverting to a previous state is as easy as
// set the data again (Undo/redo made easy)
console.log('### Restoring');
freezer.set( state ); // It will log 'I was updated' on next tick
console.log(freezer.get() === state); // true
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
anonymouspro
0viewers