ForgejComponent
en

jComponent

Group state and logic in a jComponent plugin

jComponent 20 · jcomponent@20 jcomponentfrontendplugins Executed with jComponent 20

A plugin is the controller of a section of the page. PLUGIN(name, declaration) registers it and <ui-plugin path="name"> attaches it to an element. Inside the section, ? in a path means "the path of the plugin", so the markup does not depend on where the plugin lives in the state.

The declaration receives self (the plugin instance) and config. self.get() and self.set() work relative to the plugin path, and self.element is the jQuery element of the <ui-plugin>. Implement self.make to run code once the plugin is ready. Use self.element for DOM events: self.on() is for jComponent events, not for clicks.

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