ForgejComponent
pt

jComponent

Agrupar estado e lógica num plugin jComponent

jComponent 20 · jcomponent@20 jcomponentfrontendplugins Executada com jComponent 20

Um plugin é o controlador de uma secção da página. PLUGIN(name, declaration) regista-o e <ui-plugin path="name"> associa-o a um elemento. Dentro da secção, ? num caminho significa "o caminho do plugin", pelo que a marcação não depende do sítio onde o plugin vive no estado.

A declaração recebe self (a instância do plugin) e config. self.get() e self.set() trabalham relativamente ao caminho do plugin, e self.element é o elemento jQuery do <ui-plugin>. Implemente self.make para executar código quando o plugin estiver pronto. Use self.element para eventos do DOM: self.on() serve para eventos do jComponent, não para cliques.

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-plugin path="cart">
		<p>Items: <ui-bind path="?.items" config="text:value || 0"></ui-bind></p>
		<button type="button" id="add">Add item</button>
	</ui-plugin>

	<script>

		PLUGIN('cart', function(self) {

			self.add = function() {
				self.set('items', (self.get('items') || 0) + 1);
			};

			// make() runs when the plugin is ready: initialize the state and the events here
			self.make = function() {
				self.set('items', 0);
				self.element.on('click', '#add', self.add);
			};

		});

	</script>

</body>
</html>
Experimente no seu navegador

Edite o exemplo e execute-o. Corre numa moldura isolada do seu navegador; nada é enviado para o nosso servidor.

Pré-visualização