if.bind, repeat.for, with.bind, promise.bind, swap.bind and portal appear to be a part of the template language, however none of them are particular. Every one is a customized attribute with isTemplateController: true in its definition, and the supply for all of them sits in a single folder of @aurelia/runtime-html. Nothing they do is off limits to your personal code.
This submit builds two of them from scratch. The primary, media, renders its factor solely whereas a CSS media question matches. The second, clock, provides a $now variable that the template inside it will possibly bind to. Between them they cowl practically all the pieces a template controller can do.
What makes it a template controller
A standard customized attribute is handed the factor it sits on and will get to alter it. A template controller isn’t handed that factor in any respect. When the compiler finds one, it lifts the factor out of the template, compiles it right into a separate view, and places a pair of remark markers the place the factor was once.
Take this markup:
<nav media="(min-width: 768px)">Hello ${identify}</nav>
<p>after</p>
Whereas the question doesn’t match, the DOM accommodates solely the markers:
<!--au-start--><!--au-end--><p>after</p>
And whereas it does, the view sits between them:
<!--au-start--><nav>Hello Dwayne</nav><!--au-end--><p>after</p>
The media attribute itself by no means reaches the web page. The compiled <nav> belongs to the controller now, and the controller will get three issues to work with:
IViewFactorycreates views from the compiled factor. You possibly can name it as many instances as you want, which is howrepeatrenders an inventory.IRenderLocationis theau-endmarker. A view inserts its nodes simply earlier than it.this.$controlleris the controller Aurelia creates in your attribute. It holds the presentscopeand tells you whether or not you’re energetic.
Your job is to determine when to create a view, when to activate it, which scope to present it, and when to take it away once more. That’s your complete contract.
Earlier than you construct one, examine you want one. If you wish to change a component that all the time exists (add a category, arrange a tooltip, hear for clicks), write a daily customized attribute. You want a template controller solely when the query is whether or not the content material exists, what number of copies of it exist, or what scope it binds towards.
Responsive layouts often get by on CSS. Typically, although, hiding one thing isn’t sufficient: a heavy chart you don’t need on telephones in any respect, or a desktop navigation element that does its personal setup work in hooked up. A standard repair is to take heed to matchMedia in a element, retailer a boolean, and if.bind on it. That works, however each element that wants it repeats the listener code. A template controller does the job as soon as:
<desktop-nav media="(min-width: 768px)"></desktop-nav>
<mobile-nav media="(max-width: 767px)"></mobile-nav>
Right here’s the entire thing:
import {
bindable,
IRenderLocation,
IViewFactory,
IWindow,
resolve,
templateController,
} from 'aurelia';
import sort {
ControllerVisitor,
ICustomAttributeController,
IHydratedController,
ISyntheticView,
} from '@aurelia/runtime-html';
@templateController({
identify: 'media',
defaultProperty: 'question',
noMultiBindings: true,
})
export class Media {
@bindable question = '';
readonly $controller!: ICustomAttributeController<this>;
non-public readonly manufacturing facility = resolve(IViewFactory);
non-public readonly location = resolve(IRenderLocation);
non-public readonly window = resolve(IWindow);
non-public view?: ISyntheticView;
non-public mql?: MediaQueryList;
attaching(initiator: IHydratedController) {
this.hear();
return this.replace(initiator);
}
detaching(initiator: IHydratedController) {
this.stopListening();
void this.view?.deactivate(initiator, this.$controller);
}
queryChanged() {
if (!this.$controller.isActive) return;
this.stopListening();
this.hear();
void this.replace();
}
settle for(customer: ControllerVisitor) {
return this.view?.settle for(customer);
}
dispose() {
this.view?.dispose();
this.view = undefined;
}
non-public hear() {
this.mql = this.window.matchMedia(this.question);
this.mql.addEventListener('change', this.onChange);
}
non-public stopListening() {
this.mql?.removeEventListener('change', this.onChange);
this.mql = undefined;
}
non-public onChange = () => {
void this.replace();
};
non-public replace(initiator?: IHydratedController) {
const { $controller } = this;
if (this.mql?.matches) {
const view = this.view ??= this.manufacturing facility.create($controller).setLocation(this.location);
return view.activate(initiator ?? view, $controller, $controller.scope);
}
if (this.view) {
return this.view.deactivate(initiator ?? this.view, $controller);
}
}
}
The controller sorts are imported from @aurelia/runtime-html. The aurelia package deal already depends upon it, so there’s nothing additional to put in, but when your package deal supervisor is strict about undeclared dependencies, add it to package deal.json. Then register the category like another useful resource:
Aurelia
.register(Media)
.app(MyApp)
.begin();
Now let’s undergo it.
The definition, and a colon drawback
@templateController takes the identical choices as @customAttribute, minus isTemplateController (it units that for you). Two of the choices right here matter.
defaultProperty: 'question' says which bindable will get the attribute’s worth. With out it, Aurelia appears for a bindable known as worth, which is what the built-in if makes use of. question reads higher within the class.
noMultiBindings: true is the one that may catch you out. Customized attributes help a shorthand for setting a number of bindables without delay:
<div my-tooltip="textual content: Save adjustments; place: high"></div>
The compiler decides whether or not a price makes use of this syntax by searching for a colon. Media queries are stuffed with colons, so with out the flag, (min-width: 768px) will get learn as an instruction to bind a property known as (min-width, and compilation fails with:
AUR0707: Template compilation error: creating binding to non-bindable property (min-width on media.
Any attribute whose worth may legitimately include a colon (a time, a URL, a CSS declaration) wants noMultiBindings: true.
Creating the view lazily
All the actual work occurs in replace(). When the question matches, it creates the view if there isn’t one but and prompts it. When it stops matching, it deactivates the view.
Two particulars are value stating. First, the view is created on first use, not up entrance, so a <desktop-nav> behind a question that by no means matches on a telephone isn’t instantiated. Its constructor doesn’t run and none of its bindings are created.
Second, replace() doesn’t examine whether or not the view is already energetic earlier than activating it, or already inactive earlier than deactivating it. It doesn’t must. Activating an energetic view and deactivating an inactive one each do nothing, so that you don’t want to trace that state your self.
setLocation(this.location) tells the view the place its nodes go. Activating the view inserts them earlier than the au-end marker, and deactivating it takes them again out. The view retains its nodes and bindings whereas it’s inactive, so turning it again on is affordable.
Who began this?
Each activate and deactivate name takes an initiator as its first argument. That is the controller that began the present lifecycle, and Aurelia makes use of it to trace when all the pieces in that lifecycle (together with async hooks) has completed.
There are two conditions, they usually get completely different initiators:
- In
attachinganddetaching, your controller is being added or eliminated as a part of one thing greater, similar to a route change or a father or motherifflipping. Go theinitiatoryou got, so the view’s lifecycle is a part of that bigger operation. Return the activation promise fromattaching, and the father or mother waits for it earlier than it counts as hooked up. - When one thing occurs by itself (the media question adjustments or a bindable adjustments), there’s no father or mother operation. The view turns into its personal initiator, which is what
initiator ?? viewdoes.
detaching calls deactivate with void in entrance, and that’s deliberate. As a result of the father or mother’s initiator was handed in, the deactivation is already tracked as a part of the father or mother’s teardown, so there’s nothing to return. This is identical sample the built-in if makes use of.
Bindable adjustments
queryChanged() runs at any time when the certain question adjustments, so media.bind="breakpoints.desktop" works too. It may well additionally run earlier than the controller has been hooked up, which is why it returns early if $controller.isActive is fake. In that case attaching will choose up the present worth anyway.
Cleansing up
Three items deal with teardown:
detachingstops listening tomatchMedia, so a controller that’s been eliminated doesn’t react to window resizes.attachingbegins listening once more if the content material comes again, for instance inside anifthat toggles.dispose()runs when Aurelia is completed with the controller for good. The controller created the view, so it owns it and has to get rid of it.settle for()lets Aurelia stroll the controller tree by means of your view. Go away it out and options that search the tree, such because the router discovering viewports, can’t see something rendered inside your controller.
Why resolve(IWindow)?
You could possibly name window.matchMedia instantly. Resolving IWindow from DI retains the controller away from globals, so it will possibly run underneath a non-browser platform, and a take a look at can register a pretend window and swap the question on and off at will. Extra on that additional down.
Constructing clock: giving a view its personal scope
media fingers its view the scope it was given, so the content material binds precisely as if the controller weren’t there. A template controller may give the view a distinct scope, and that’s how repeat gives $index and with adjustments what this factors at.
Right here’s a controller that provides a $now variable and refreshes it on an interval:
<p clock.bind="1000">Final refreshed ${$now.toLocaleTimeString()}</p>
import {
bindable,
IRenderLocation,
IViewFactory,
resolve,
Scope,
templateController,
} from 'aurelia';
import sort {
ControllerVisitor,
ICustomAttributeController,
IHydratedController,
ISyntheticView,
} from '@aurelia/runtime-html';
@templateController('clock')
export class Clock {
@bindable worth = 1000;
readonly $controller!: ICustomAttributeController<this>;
non-public readonly manufacturing facility = resolve(IViewFactory);
non-public readonly location = resolve(IRenderLocation);
non-public readonly context = { $now: new Date() };
non-public view?: ISyntheticView;
non-public timer?: ReturnType<typeof setInterval>;
attaching(initiator: IHydratedController) {
this.begin();
const { $controller } = this;
const view = this.view ??= this.manufacturing facility.create($controller).setLocation(this.location);
const scope = Scope.fromParent($controller.scope, this.context);
return view.activate(initiator, $controller, scope);
}
detaching(initiator: IHydratedController) {
this.cease();
void this.view?.deactivate(initiator, this.$controller);
}
valueChanged() {
if (!this.$controller.isActive) return;
this.cease();
this.begin();
}
settle for(customer: ControllerVisitor) {
return this.view?.settle for(customer);
}
dispose() {
this.view?.dispose();
this.view = undefined;
}
non-public begin() {
this.context.$now = new Date();
this.timer = setInterval(() => {
this.context.$now = new Date();
}, Quantity(this.worth) || 1000);
}
non-public cease() {
clearInterval(this.timer);
}
}
The one new line is that this one:
const scope = Scope.fromParent($controller.scope, this.context);
Scope.fromParent creates a scope with this.context as its binding context and the controller’s personal scope as its father or mother. When a binding contained in the view appears up a reputation, it checks this.context first after which works its approach up by means of the father or mother scopes. So ${$now} resolves to the clock, and all the pieces else (${label}, occasion handlers, worth converters) nonetheless resolves towards the element, the identical as earlier than.
You don’t must do something particular to make $now reactive. this.context is a plain object, and Aurelia observes it the identical approach it observes your element properties. Assigning a brand new Date updates each binding that reads it.
The $ prefix is a conference, not syntax. As a result of lookups examine the interior scope first, a variable known as now would cover any now property on the element, and the bug that causes is tough to identify. Constructed-in variables like $index and $earlier use the prefix for a similar cause, so it’s value copying.
Issues that may journey you up
Order issues when there’s multiple. If a component has a number of template controllers, the compiler processes them from proper to left. The rightmost one will get the compiled factor, and each to its left wraps the one beside it. In repeat.for="merchandise of things" if.bind="merchandise.seen", each repeated row will get its personal if. Swap the 2 attributes and you’ve got one if wrapping your complete record.
Not each place can host one. Template controllers can’t go on a surrogate <template as-element="...">, and unfold bindings (...$attrs) skip them. Each throw compiler errors that say so.
Fast adjustments and async hooks. If the content material inside your controller has async attaching or detaching hooks, a second change can arrive whereas the primary remains to be in progress. Neither instance right here guards towards that, and for many controllers it doesn’t matter. If yours flips rapidly and wraps sluggish parts, learn how the built-in
if
retains a pending promise and a swap counter, so an outdated change can’t end after a more recent one.
Sharing a container. By default each view a controller creates shares the DI container it was created in. If every view wants its personal youngster container, for instance so each will get its personal occasion of a service, add containerStrategy: 'new' to the definition. The built-in promise controller does this.
Testing it
Controllers are straightforward to check with createFixture from @aurelia/testing. That is the place resolving IWindow pays off, as a result of the take a look at can hand the controller a window whose matchMedia it controls:
import { Registration } from 'aurelia';
import { IWindow } from '@aurelia/runtime-html';
import { tasksSettled } from '@aurelia/runtime';
import { assert, createFixture } from '@aurelia/testing';
it('renders solely whereas the question matches', async () => {
const media = fakeMatchMedia(); // a stub that lets the take a look at flip `matches`
media.set('(min-width: 768px)', true);
const { appHost } = createFixture(
`<nav media="(min-width: 768px)">Menu</nav>`,
class App {},
[Media, Registration.instance(IWindow, media.window)],
);
assert.strictEqual(appHost.querySelector('nav')?.textContent, 'Menu');
media.set('(min-width: 768px)', false);
await tasksSettled();
assert.strictEqual(appHost.querySelector('nav'), null);
});
Check the teardown as properly. Wrap the controller in an if, toggle it off, and assert that the change listener was eliminated. A template controller that leaks listeners received’t throw something. Your app will simply get somewhat slower each time the person navigates.
The place to go subsequent
The built-in controllers are the most effective reference there may be, they usually’re quick.
with
is underneath 100 strains and really near clock.
if
reveals find out how to handle two views and deal with async swaps.
repeat
reveals how far you’ll be able to take it. The
template controllers web page
within the docs covers hyperlink(), which else makes use of to connect itself to the if earlier than it.
Should you construct one thing good with this, present us on
Discord
. I’d prefer to see a feature-flag controller that isn’t a hand-rolled if.bind="flags.has('x')" in each element.

