Write a custom jComponent
A component is declared with COMPONENT(name, config, declaration). The second argument is the default configuration as a string (key:value;key:value). The declaration receives self (the component instance) and config (the parsed configuration).
self.makeruns once, when the component is created. Build the DOM here.self.setter(value)runs every time the value of the component'spathchanges.self.set(value)writes a new value to thepath;self.get()reads it.
Use the component with a <ui-component> element. name selects the declaration, path the state and config overrides the defaults.
<!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>
<ui-component name="counter" path="cart.count" config="step:2"></ui-component>
<p>Total: <ui-bind path="cart.count" config="text:value"></ui-bind></p>
<script>
COMPONENT('counter', 'step:1', function(self, config) {
self.make = function() {
self.html('<button type="button">Add</button> <b class="value">0</b>');
self.event('click', 'button', function() {
self.set((self.get() || 0) + config.step);
});
};
self.setter = function(value) {
self.find('.value').text(value || 0);
};
});
SET('cart.count', 10);
</script>
</body>
</html>The ui-bind next to the component shows that both read the same state: clicking the button changes the path and every element bound to it updates.
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