ForgejComponent
en

jComponent

Send events between components with ON and EMIT

jComponent 20 · jcomponent@20 jcomponentfrontendevents Executed with jComponent 20

Global events let independent parts of a page talk without knowing each other. ON(name, callback) registers a listener, EMIT(name, a, b, c, d) calls every listener with up to four arguments, and OFF(name, [callback]) removes one listener or all the listeners of the name. Components and plugins have the same functions on self (self.on(), self.emit()), and the listeners they register are removed together with the component.

EMIT('cart.changed', 3)   ->   ON('cart.changed', function(count) { ... })
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"></ui-component>
	<p class="shown"></p>

	<script>

		var received = [];

		COMPONENT('counter', function(self) {
			self.make = function() {
				self.html('<button type="button">+1</button>');
				var count = 0;
				self.find('button').on('click', function() {
					EMIT('cart.changed', ++count, 'button');
				});
			};
		});

		function listener(count, source) {
			received.push(count + ':' + source);
			$('.shown').text('Count: ' + count);
		}

		ON('cart.changed', listener);

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