---
title: Creating components
project: jComponent V19
version: 19.194
section: guides
language: en
license: MIT
url: https://totaljs.es/docs/jcomponent-v19/19-194/guides/creating-components/
updated: 2026-11-18T13:55:49.124Z
---

# Creating components

> Declare your own components, handle their lifecycle, and exchange data with the model.

You declare a component once with [COMPONENT()](../../reference/globals/) and then place it on as many pages as you need. This guide builds up the API step by step. To place existing components, read [Using components](../using-components/).

## Declare a component

```html
<ui-component name="hello" path="visitor"></ui-component>

<script>
	COMPONENT('hello', function(self, config, cls) {

		self.make = function() {
			self.aclass(cls);
		};

		self.setter = function(value) {
			self.text('Hello ' + (value || 'stranger'));
		};
	});

	SET('visitor', 'Ana');
</script>
```

The element renders as `<ui-component name="hello" path="visitor" class="ui-hello">Hello Ana</ui-component>`.

`COMPONENT(name, [config], declaration, [dependencies])` takes these arguments:

| Argument | Description |
| --- | --- |
| `name` | The name of the component. |
| `config` | The default configuration, as a string such as `'size:1;color:red'` or as an object. |
| `declaration` | A function that runs for each instance. |
| `dependencies` | An array of what must load first. |

The declaration receives three arguments:

| Argument | Description |
| --- | --- |
| `self` | The instance of the component. |
| `config` | The configuration of this instance. |
| `cls` | A CSS class name made of `ui-` and the name of the component. |

## The lifecycle

You define the functions below on `self`, and the library calls them in this order. All of them are optional.

```html
<ui-component name="life" path="demo.value" config="size:3"></ui-component>

<script>
	COMPONENT('life', 'size:1', function(self, config, cls) {

		console.log('1 declaration', cls, config.size);

		self.init = () => console.log('2 init');
		self.make = () => console.log('3 make');

		self.configure = function(key, value, init) {
			if (key === 'size')
				console.log('4 configure', key, value, init);
		};

		self.setter = (value, path, type) => console.log('5 setter', value, path, type);

		self.validate = function(value) {
			console.log('6 validate', value);
			return true;
		};

		self.state = (type, what) => console.log('7 state', type, what);
		self.done = () => console.log('8 done');
		self.destroy = () => console.log('9 destroy');
	});

	SET('demo.value', 'A');

	setTimeout(() => FIND('life').remove(), 600);
</script>
```

| Function | When it runs |
| --- | --- |
| `init()` | One time for each component name, with the first instance. |
| `make()` | When the instance is created. Build the content here. |
| `configure(key, value, init, prev)` | For each configuration key, and again whenever a key changes. |
| `setter(value, path, type)` | With the initial value, and whenever the value changes. |
| `validate(value)` | After the setter. Returns `true` for a valid value. |
| `state(type, what)` | When the state of the component changes. |
| `done()` | Shortly after the component is ready. |
| `destroy()` | When the component is removed. |

During initialization, `configure` also runs for the state keys `modified`, `touched` and `invalid`, with `init` set to `true`.

## Receive data

`self.setter` receives the value, the path that changed and the type of the change.

```html
<ui-component name="spy" path="demo.value" default="'initial'"></ui-component>

<script>
	COMPONENT('spy', function(self) {
		self.setter = function(value, path, type) {
			console.log(value, type);
		};
	});

	ON('ready', function() {
		SET('demo.value', 'manual');        // manual 1
		FIND('spy').set('input', 2);        // input 2
		DEFAULT('demo.value');              // initial 3
	});
	// initial 0
</script>
```

| Type | Meaning |
| --- | --- |
| `0` | The initial value. |
| `1` | Changed by code. |
| `2` | Changed by user input. |
| `3` | Set to the default value. |

## Read the configuration

The `config` object always holds the current values. Use `self.configure` to react to changes, and check the `init` argument to tell the first run from later ones. `self.refresh()` runs the setter again with the current value.

```html
<ui-component name="meter" path="level" config="max:10;color:green"></ui-component>

<script>
	COMPONENT('meter', 'max:100;color:gray', function(self, config) {

		self.configure = function(key, value, init, prev) {
			switch (key) {
				case 'color':
					self.css('color', value);
					!init && console.log('color', prev, '->', value);
					break;
				case 'max':
					!init && self.refresh();
					break;
			}
		};

		self.setter = function(value) {
			self.text(value + ' / ' + config.max);
		};
	});

	SET('level', 7);

	ON('ready', function() {
		FIND('meter').reconfigure('color:red;max:20');
		// color green -> red
	});
</script>
```

The element renders `7 / 20` in red after the call to `reconfigure()`.

## Write data

| Method | Description |
| --- | --- |
| `self.get()` | Reads the value at the path of the component. |
| `self.set(value, [type])` | Writes the value and marks the component as modified. The setter runs too. |
| `self.modify(value, [type])` | Runs the parsers, marks the component as touched and writes the value with type `2`. |
| `self.getter(value)` | Runs the parsers, marks the component as touched and writes the value if it changed. |
| `self.bind(flags, value)` | Writes the value without running the setter, and applies the flags. |
| `self.skip()` | Skips the next run of the setter. |

The flags of `self.bind()` are `@touched`, `@modified`, `@reset`, `@validate` and `@setter`. The last one makes the setter run after all.

```html
<ui-component name="stepper" path="qty"></ui-component>

<script>
	COMPONENT('stepper', function(self) {

		self.make = function() {
			self.html('<button>-</button> <b></b> <button>+</button>');
			self.event('click', 'button', function() {
				var diff = this.textContent === '+' ? 1 : -1;
				self.bind('@touched @modified', (self.get() || 0) + diff);
				self.find('b').text(self.get());
			});
		};

		self.setter = function(value) {
			console.log('setter', value);
			self.find('b').text(value);
		};
	});

	SET('qty', 1);    // setter 1
</script>
```

Clicking `+` twice leaves `qty` at `3`, and the setter does not run for these clicks. A later `SET('qty', 9)` runs it as usual.

## Connect a text input

An `<input>`, `<textarea>` or `<select>` with the `data-jc-bind` attribute works without further code: the library copies the value in both directions, and checkboxes write `true` or `false`. A `formatter` changes how the value is displayed. The setting `type:number` makes the library store a number instead of a string.

```html
<ui-component name="price" path="item.price" config="type:number"></ui-component>

<script>
	COMPONENT('price', function(self) {

		self.make = function() {
			self.html('<input type="text" data-jc-bind="" />');
		};

		self.formatter(function(path, value) {
			return value == null ? '' : value.format(2);
		});
	});

	SET('item.price', 5);
</script>
```

The input shows `5.00`. Typing `12.5` stores the number `12.5`.

These configuration keys control when an input writes its value:

| Key | Effect |
| --- | --- |
| `$delay:500` | Waits this many milliseconds after the last key press. The default is `200`. |
| `$realtime:false` | Writes the value when the input loses focus. |

```html
<ui-component id="slow" name="box" path="form.slow" config="$delay:500"></ui-component>
<ui-component id="blur" name="box" path="form.blur" config="$realtime:false"></ui-component>

<script>
	COMPONENT('box', function(self) {
		self.make = function() {
			self.html('<input type="text" data-jc-bind="" />');
		};
	});
</script>
```

## Build a custom input

For your own controls, call `self.getter()` with the new value. A `parser` converts what the user entered into the stored value, and a `formatter` does the opposite. Both receive the path, the value, the type and the format.

```html
<ui-component name="tags" path="post.tags"></ui-component>

<script>
	COMPONENT('tags', function(self) {

		self.make = function() {
			self.html('<input type="text" />');
			self.event('change', 'input', function() {
				self.getter(this.value);
			});
		};

		self.parser(function(path, value) {
			return value.split(',').map(tag => tag.trim());
		});

		self.formatter(function(path, value) {
			return (value || []).join(', ');
		});

		self.setter = function(value) {
			self.find('input').val(self.formatter(value));
		};
	});

	SET('post.tags', ['a', 'b']);
</script>
```

The input shows `a, b`. Entering `x, y ,z` stores `["x","y","z"]`.

## Validate the value

`self.validate` returns `true` for a valid value. `self.isInvalid()` returns `true` when the value is invalid and the user already touched the component, which is the right moment to show an error.

```html
<ui-component id="mail" name="email" path="user.email"></ui-component>

<script>
	COMPONENT('email', function(self, config) {

		self.make = function() {
			self.html('<input type="text" data-jc-bind="" /><small>Enter a valid address</small>');
		};

		self.validate = function(value) {
			return (value || '').isEmail();
		};

		self.state = function() {
			self.find('small').tclass('hidden', !self.isInvalid());
		};
	});
</script>
```

The message stays hidden on the empty form, appears after `nope` and disappears again after `a@b.io`. [Forms and validation](../forms/) covers whole forms.

## Keep internal data

`self.data(key, value)` stores a value inside the component. A binding inside the component reads it with a path that starts with `@`. `@` alone is the value of the component, and `@config.name` is a configuration key.

```html
<ui-component name="card" path="person.name" config="title:Profile"></ui-component>

<script>
	COMPONENT('card', 'title:Untitled', function(self) {

		self.make = function() {
			self.html('<h3><ui-bind path="@config.title" config="text"></ui-bind></h3>'
				+ '<p><ui-bind path="@" config="text"></ui-bind></p>'
				+ '<small><ui-bind path="@visits" config="text"></ui-bind></small>');
			self.data('visits', 1);
		};

		self.setter = NOOP;
	});

	SET('person.name', 'Ana');
</script>
```

## Declare dependencies

The fourth argument of `COMPONENT()` lists what must be available when the component starts. `make` waits for all of them.

| Item | Description |
| --- | --- |
| A function | Receives a `next` function to call when it finishes. |
| A URL | A script or stylesheet that is imported one time. |
| `@name` | Another component, downloaded if it is missing. |

```html
<ui-component name="chart" path="stats"></ui-component>

<script>
	COMPONENT('chart', function(self) {
		self.make = function() {
			console.log('make', window.chartlib);
		};
	}, [function(next) {
		setTimeout(function() {
			window.chartlib = 'loaded';
			next();
		}, 100);
	}]);
</script>
```

## Work inside a scope

When a component is inside a [scope](../scopes/), `self.makepath()` turns `?` into the path of the scope. `self.GET()` and `self.SET()` do this for you.

```html
<ui-plugin path="order">
	<ui-component name="total" path="?.items" config="target:?.sum"></ui-component>
</ui-plugin>

<script>
	COMPONENT('total', function(self, config) {
		self.setter = function(value) {
			var sum = (value || []).reduce((a, b) => a + b, 0);
			self.SET(config.target, sum);
			console.log(self.path, self.makepath(config.target), self.GET(config.target));
		};
	});

	SET('order.items', [10, 20]);
</script>
```

## Watch other data

| Method | Description |
| --- | --- |
| `self.watch(path, fn, [init])` | Watches a path while the component exists. |
| `self.on(name, fn)` | Listens to a global event while the component exists. |
| `self.datasource(path, fn)` | Watches a path and calls the function with the current value once the configuration is loaded. |
| `self.command(name, fn)` | Registers a command for [CMD()](../../reference/globals/). |
| `self.event(type, [selector], fn)` | Adds a DOM event listener to the element. |

```html
<ui-component name="filter" path="query" config="source:shop.colors"></ui-component>

<script>
	COMPONENT('filter', function(self, config) {

		self.make = function() {
			self.watch('shop.total', (path, value) => console.log('watch', value));
			self.on('reload', reason => console.log('event', reason));
			self.datasource(config.source, (path, value, type) => console.log('datasource', value, type));
		};
	});

	SET('shop.colors', ['red']);

	ON('ready', function() {
		SET('shop.total', 5);            // watch 5
		EMIT('reload', 'manual');        // event manual
		SET('shop.colors', ['blue']);    // datasource ["blue"] 1
	});
	// datasource ["red"] 0
</script>
```

## Limit when the setter runs

| Method | Effect |
| --- | --- |
| `self.bindchanges()` | Skips the setter when the value is the same as the last one. |
| `self.bindexact()` | Skips the setter for changes made to paths below the path of the component. |

```html
<ui-component name="once" path="a.b"></ui-component>

<script>
	COMPONENT('once', function(self) {

		self.bindchanges();
		self.bindexact();

		self.setter = function(value, path, type) {
			console.log('setter', JSON.stringify(value), type);
		};
	});

	ON('ready', function() {
		SET('a.b', { c: 1 });     // setter {"c":1} 1
		SET('a.b', { c: 1 });     // (same value, skipped)
		SET('a.b.c', 2);          // (nested path, skipped)
	});
	// setter undefined 0
</script>
```

## Work with the element

| Member | Description |
| --- | --- |
| `self.element` | The element, as a jQuery object. |
| `self.find(selector)` | Finds elements inside the component. |
| `self.html(value)` | Replaces the content with HTML. |
| `self.text(value)` | Replaces the content with text. |
| `self.aclass(name)` | Adds a CSS class. |
| `self.css(name, value)` | Sets a CSS property. |

The [Component](../../reference/component/) reference lists every method.

## A complete component

This rating control combines configuration, rendering, user input and a binding on the same path.

```html
<ui-component name="rating" path="review.stars" config="max:5;icon:*"></ui-component>
<p><ui-bind path="review.stars" config="text:value + ' of 5'"></ui-bind></p>

<script>
	COMPONENT('rating', 'max:5;icon:#', function(self, config, cls) {

		self.make = function() {
			self.aclass(cls);
			self.event('click', 'span', function() {
				self.bind('@touched @modified @setter', +this.getAttribute('data-value'));
			});
		};

		self.configure = function(key, value, init) {
			!init && self.refresh();
		};

		self.setter = function(value) {
			var builder = [];
			for (var i = 1; i <= config.max; i++)
				builder.push('<span data-value="' + i + '" class="' + (i <= value ? 'on' : '') + '">' + config.icon + '</span>');
			self.html(builder.join(''));
		};
	});

	SET('review.stars', 3);
</script>
```

The control starts with three active stars and the text `3 of 5`. Clicking the fifth star stores `5` and updates the text.
