ForgejComponent
en

jComponent

Read, change and watch the state

jComponent 20 · jcomponent@20 jcomponentfrontendstate Executed with jComponent 20

The state is one global object addressed by paths such as cart.items. The functions to work with it:

  • SET(path, value) writes a value and notifies everything bound to the path
  • GET(path) reads a value
  • UPD(path) notifies the path after you changed the object in place (GET('cart').discount = 5; UPD('cart'))
  • PUSH(path, value) appends to an array and notifies; with a ^ before the path it adds the value to the beginning
  • WATCH(path, callback) runs the callback with the new value every time the path changes; join several paths with +
public/index.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
	<title>jComponent</title>
	<link rel="stylesheet" href="//cdn.componentator.com/spa.min@20.css" />
	<script src="//cdn.componentator.com/spa.min@20.js"></script>
</head>
<body>
	<p><ui-bind path="cart.items" config="text:value ? value.length + ' items' : 'empty'"></ui-bind></p>

	<script>

		var log = [];

		WATCH('cart.items', function(value) {
			log.push(value.length);
		});

		SET('cart.items', []);
		PUSH('cart.items', 'book');
		PUSH('^cart.items', 'pen');

		GET('cart.items').push('lamp');
		UPD('cart.items');

	</script>

</body>
</html>
Try it in your browser

Edit the example and run it. It runs in an isolated frame in your browser; nothing is sent to our server.

Preview