# Escrever um componente jComponent próprio

> Registe um componente reutilizável com COMPONENT(), renderize-o em make(), reaja a mudanças de estado em setter() e escreva de volta com set().

Framework: jcomponent20
Product: jComponent 20 (jcomponent@20)
Language: pt
Content-SHA256: 6e77f4e67729d701783e0ac2ab750b175ec2661002f400e7ce2488d96493be08
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: jcomponent20@3fedd009a277f50fddc608b97afbec553b67c51b
Review: not-recorded

Um componente declara-se com `COMPONENT(name, config, declaration)`. O segundo argumento é a configuração por omissão como string (`key:value;key:value`). A declaração recebe `self` (a instância do componente) e `config` (a configuração interpretada).

- `self.make` corre uma vez, quando o componente é criado. Construa aqui o DOM.
- `self.setter(value)` corre sempre que o valor do `path` do componente muda.
- `self.set(value)` escreve um novo valor no `path`; `self.get()` lê-o.

Use o componente com um elemento `<ui-component>`. `name` escolhe a declaração, `path` o estado e `config` substitui os valores por omissão.

```html 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>

	<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>
```

O `ui-bind` ao lado do componente mostra que ambos leem o mesmo estado: clicar no botão altera o caminho e todos os elementos ligados a ele atualizam-se.
