API
Component ⇐ View
Components are a special kind of View that is designed to be easily composable,
making it simple to add child views and build complex user interfaces.
Unlike views, which are render-agnostic, components have a specific set of rendering
guidelines that allow for a more declarative development style.
A component renders from its template method, which returns a partial (built with partial) or a child component. Let the Component.create static method write it from a template function, the shortest form for presentational components; define it in a subclass, for components with methods or state; or pass create a tagged template string, whose interpolations are defined with the declaration, so dynamic values must be functions.
Extends: View
See: Component.create
| Param | Type | Description |
|---|---|---|
| options | object |
Object containing options. The following keys will be merged to this: model, state, key, onDestroy, onHydrate, onBeforeRecycle, onRecycle, onBeforeUpdate, onUpdate, onCreate, onChange. Any additional options not in the component or view options list will be automatically extracted as props and stored as this.props. |
Properties
| Name | Type | Description |
|---|---|---|
| [key] | string | number |
A unique key to identify the component. Components with keys are recycled when a previous child of the same class with the same key is found in the previous render of the same interpolation. Unkeyed components are recycled by type and position for a single value, but are never recycled inside an array. Keys are compared by identity, so 1 and '1' are different keys. |
| [model] | Model |
A Model or any emitter object containing data and business logic. The component will listen to change events and call onChange lifecycle method. |
| [state] | Model |
A Model or any emitter object containing data and business logic, to be used as internal state. The component will listen to change events and call onChange lifecycle method. |
| props | Model |
Automatically created from any options not merged to the component instance. Contains props passed from parent component, to be read. A plain object in the constructor, then a Model from the first render on, built by createProps: the component will listen to change events on props and call onChange lifecycle method. When the component is recycled during a parent re-render, its props are set again and any change triggers a re-render. Props are compared by identity, so a function, object or array created during the parent's render counts as a change every time. |
| html | function |
Alias of partial, bound to the component instance. Not set when a subclass defines its own html. |
Example
import { Component, Model } from 'rasti';
// Create Timer component.
class Timer extends Component {
template() {
return this.html`
<div>
Seconds: <span>${this.model.seconds}</span>
</div>
`;
}
}
// Create model to store seconds.
const model = new Model({ seconds : 0 });
// Mount timer on body.
Timer.mount({ model }, document.body);
// Increment `model.seconds` every second.
setInterval(() => model.seconds++, 1000);
- Component ⇐
View- instance
- .createProps(props) ⇒
Model - .provide() ⇒
object|null - .inject(key) ⇒
Model - .subscribe(model, [type], [listener]) ⇒
Component - .partial(strings, …expressions) ⇒
ComponentPartial - .template() ⇒
ComponentPartial|Component - .toString() ⇒
string - .render() ⇒
Component - .onCreate(…args)
- .onChange(model, changed)
- .onHydrate()
- .onBeforeRecycle()
- .onRecycle()
- .onBeforeUpdate()
- .onUpdate()
- .onDestroy(…args)
- .createProps(props) ⇒
- static
- .markAsSafeHTML(value) ⇒
object - .extend(object)
- .mount([options], [containerEl], [shouldHydrateExistingDOM]) ⇒
Component - .create(strings, …expressions) ⇒
Component
- .markAsSafeHTML(value) ⇒
- instance
component.createProps(props) ⇒ Model
Build the Model the component keeps its props in. Called once, on the first
render, with the options the parent passed that are not component or view
options; until then this.props is that plain object.
Override it to give props a model of your own — one with defaults, or one that
validates what a parent passes.
Kind: instance method of Component
Returns: Model - The model to keep the props in.
| Param | Type | Description |
|---|---|---|
| props | object |
The props the component was mounted with. |
Example
const Button = Component.create`<button>${({ props }) => props.label}</button>`.extend({
createProps(props) {
return new ButtonProps(props);
}
});
component.provide() ⇒ object | null
Provide contexts to the components this one hosts, at any depth: its children, including the content slotted into it, and their own. Called on every render, before the template's children render.
Return an object mapping each context key to the values of that context, or null
to provide nothing. Each key gets one Model, created on the first render and
set with the returned values on every later one, so return the same keys, with
the same properties, on every render (null for a value that is absent). Use
Symbol keys exported by a module of their own, so neither side imports the other.
Kind: instance method of Component
Returns: object | null - The values of each context, by key.
Example
import { Component } from 'rasti';
import { FormControl } from './form-control.js';
class Field extends Component {
provide() {
const { controlId, error } = this.props;
return { [FormControl] : { id : controlId, invalid : !!error } };
}
}
component.inject(key) ⇒ Model
Read a context provided by a parent. The search starts at this.parent and walks
up the views that adopted this one, so a component that provides a key reads its
parent's, not its own. Bound to the component instance from the first render on.
Returns the Model of the nearest parent that provides key, or a shared, empty
and frozen Model when none does: its properties read undefined, so a consumer
falls back to its own defaults. The component subscribes to each provider's model
it reads, like it does to props, and re-renders when the provided values change.
Kind: instance method of Component
Returns: Model - The context model.
| Param | Type | Description |
|---|---|---|
| key | symbol | string |
The context key. |
Example
import { Component } from 'rasti';
import { FormControl } from './form-control.js';
const Input = Component.create`
<input id="${({ props, inject }) => props.id || inject(FormControl).id}" />
`;
component.subscribe(model, [type], [listener]) ⇒ Component
Subscribes to a change event on a model or emitter object and invokes the onChange lifecycle method.
The subscription is automatically cleaned up when the component is destroyed.
By default, the component subscribes to changes on this.model, this.state, this.props,
and the contexts it reads with inject.
Kind: instance method of Component
Returns: Component - The current component instance for chaining.
| Param | Type | Default | Description |
|---|---|---|---|
| model | Object |
The model or emitter object to listen to. | |
| [type] | string |
"'change'" |
The event type to listen for. |
| [listener] | function |
this.onChange |
The callback to invoke when the event is emitted. |
component.partial(strings, …expressions) ⇒ ComponentPartial
Tagged template helper method.
Used to create a partial template.
It will return a Partial: the template's structure paired with this render's
expressions, which the component renders and then patches in place on later renders.
Components interpolated in it will be added as children by the parent component.
Template strings literals will be marked as safe HTML to be rendered.
This method is bound to the component instance by default, and is also available as this.html.
A partial used inside an interpolation may render any number of nodes, and may be swapped for a different template between renders. The partial returned by template is the component's root and is restricted on both counts.
Kind: instance method of Component
Returns: ComponentPartial - The partial to render.
| Param | Type | Description |
|---|---|---|
| strings | TemplateStringsArray |
Template strings. |
| …expressions | any |
Template expressions. |
Example
import { Component } from 'rasti';
// Create a Title component.
const Title = Component.create`
<h1>${({ props }) => props.renderChildren()}</h1>
`;
// Create Main component.
const Main = Component.create`
<main>
${self => self.renderHeader()}
</main>
`.extend({
// Render header method.
// Use `partial` to render an HTML template adding children components.
renderHeader() {
return this.partial`
<header>
<${Title}>${({ model }) => model.title}</${Title}>
</header>
`;
}
});
component.template() ⇒ ComponentPartial | Component
Return the component's root partial. Called on every render, so interpolated
values are recomputed. Override it (directly, via extend, or through create)
to define the markup. It may also return a child component instance, in which case
the component is rendered as a container around it. A root partial that is
a single component tag (this.html`<${Child} />`) makes a container too, and
builds the child only when it cannot recycle the previous one (see render). So
does returning the content slotted into it (this.props.renderChildren()), when
that content has a single root element: the component adds no element of its own,
and the components in that content are its children.
The base implementation builds the element the way a view does: from this.tag
(defaulting to div) and the component's attributes, rendering the content the
parent slotted into it (props.renderChildren). A void tag renders self-closed
and takes no content.
// <section class="panel">Content</section>
Component.mount({
tag : 'section',
attributes : { class : 'panel' },
renderChildren : () => 'Content'
}, document.body);
The root element is created on the first render and keeps its tag from then on:
later renders patch that element in place, so a tag that changes afterwards is
not applied — and one that changes between a void and a non-void tag throws, since
that does change the root template.
Two restrictions apply to the root partial, and only to it — the partials rendered inside an interpolation are free of both:
- It must have a single root element, which becomes the component's
this.el. Development builds throw when it resolves to anything else, since the nodes beside the root would be left out of every update. - It must be built from the same template on every render, since the root is patched in place; returning a different one throws. Branch inside the interpolations instead of switching the root itself.
Kind: instance method of Component
Returns: ComponentPartial | Component - The root partial, or a child component to contain.
component.toString() ⇒ string
Render the component as a string. Used internally on the render process. Use it for server-side rendering or static site generation.
Rendering is the toString contract: every piece Rasti emits answers it with
the markup it stands for, so a component goes straight into any HTML string —
interpolated into a server-side layout, or concatenated with it.
Kind: instance method of Component
Returns: string - The rendered component.
Example
import { Component } from 'rasti';
const Button = Component.create`
<button class="button">Click me</button>
`;
const App = Component.create`
<div>
<${Button}>Click me</${Button}>
</div>
`;
const app = new App();
console.log(app.toString());
// <div data-rst-el="r1-1"><!--rst-s-r1-1--><button class="button" data-rst-el="r2-1">Click me</button><!--rst-e-r1-1--></div>
console.log(`${app}`);
// <div data-rst-el="r1-1"><!--rst-s-r1-1--><button class="button" data-rst-el="r2-1">Click me</button><!--rst-e-r1-1--></div>
component.render() ⇒ Component
Render the Component.
First render (before the component is hydrated):
This is the initial render call, where template() runs for the first time. The component will be rendered
as a string inside a DocumentFragment and hydrated, making this.el available. this.el is the root DOM
element of the component that can be applied to the DOM. If the component has its own el, it hydrates onto
that existing DOM instead (server-side rendered markup).
The onHydrate lifecycle method will be called.
Note: Typically, you don't need to call render() directly for the first render. The static method Component.mount()
handles this process automatically, creating the component instance, rendering it, and appending it to the DOM.
Update render (once the component is hydrated): The component keeps its root partial and root element, and reconciles their contents recursively instead of rendering the whole tree from scratch. Elements and retained partials are patched in place, matching children are recycled, and an interpolation region is regenerated only when its occupant changes identity or shape. The method will:
- Diff and update the attributes of every element in the template and in its partials
- Reconcile the content of each interpolation (the dynamic parts of the template), updating nested partials in place
- For container components (components that render a single child component), update the single interpolation
The onBeforeUpdate lifecycle method will be called at the beginning, followed by the onUpdate lifecycle method at the end.
A render asked for while the component is rendering, its hydration included, does not interrupt it: it runs
once that render is done, after onHydrate or onUpdate.
Child component handling: When rendering child components, they can be either recreated or recycled:
Recreation: A new component instance is created, running the constructor again. This happens when no matching component is found for recycling.
Recycling: The same component instance is reused. Recycling happens in two ways:
Unkeyed components are recycled if they have the same type and position in the template or partial
Components with a
keyare recycled if a previous child of the same class with the same key occupied the same interpolationA
keyidentifies a component among the siblings of its own interpolation, which is what lets the items of a list be reordered without recreating them:items.map(item => html`<${Row} key="${item.id}" />`)reuses the rows and moves them into place. Nested arrays are one list, sogroups.map(group => group.map(…))does the same with its rows. A component inside any other partial, wrapped in markup (html`<li><${Row} key="…" /></li>`) or not (html`${Row.mount({ key : … })}`), belongs to that partial instead, and is recreated when the list reorders. Development builds warn about it.When a component is recycled:
The
onBeforeRecyclelifecycle method is called when recycling startsThe component's
this.propsis updated with the new props from the parentThe
onRecyclelifecycle method is called after props are updatedA recycled component may not use props at all and remain unchanged, or it may be subscribed to a different model (or even the same model as the parent) and update independently in subsequent render cycles.
Component tags and built components: a child written as a component tag (
html`<${Row} key="…" />`) is built only when it is recreated: when the render recycles a previous child instead, the tag's attributes go straight to it as props, and no new instance is created. A child an expression builds (Row.mount(options)ornew Row(options)) is a new instance on every render, so its constructor andonCreaterun each time; when the render recycles the previous child in its place, the new instance takes no part in the render: its props are handed to the previous one and it is destroyed, runningonDestroy. Both forms recycle the same way. Prefer the tag: it does less work on every update.
Kind: instance method of Component
Returns: Component - The component instance.
component.onCreate(…args)
Lifecycle method. Called when the component is created, at the end of the constructor.
This method receives the same arguments passed to the constructor (options and any additional parameters).
It executes both on client and server.
Use this method to define models or state that will be used later in onHydrate.
A child written as a component tag is only created when the parent's render does not
recycle a previous one. A child built in an expression (Child.mount(options) or
new Child(options)) is created on every render of its parent, and when the
previous one is recycled instead, the new one is destroyed without ever rendering.
Keep onCreate free of side effects that outlive the instance.
Kind: instance method of Component
| Param | Type | Description |
|---|---|---|
| …args | \* |
The constructor arguments (options and any additional parameters). |
component.onChange(model, changed)
Lifecycle method. Called when model emits change event.
By default calls render method.
This method can be extended with custom logic.
Maybe comparing new attributes with previous ones and calling
render when needed.
Kind: instance method of Component
| Param | Type | Description |
|---|---|---|
| model | Model |
The model that emitted the event. |
| changed | object |
Object containing keys and values that has changed. |
| […args] | any |
Any extra arguments passed to set method. |
component.onHydrate()
Lifecycle method. Called when the component is rendered for the first time and hydrated.
Its DOM is already in place: in the container it was mounted into, in the existing DOM it hydrated, or in
its parent's DOM when an update added it. A component rendered with render() alone hydrates in a detached
DocumentFragment.
A model written here reaches the components already hydrated, its ancestors included, which render once the
render in progress is done; the components hydrated after this one rendered the previous value, and show it
until the next change.
This method only executes on the client and only during the first render.
Use this method for client-only operations like making API requests or setting up browser-specific functionality.
Kind: instance method of Component
component.onBeforeRecycle()
Lifecycle method. Called before the component is recycled and reused between renders.
This method is called at the beginning of the recycle method, before any recycling operations occur.
A component is recycled when:
- It has a
keyand a previous child of the same class with the same key exists - It doesn't have a
keybut has the same type and position in the template or partial
Use this method to perform operations that need to happen before the component is recycled, such as storing previous state or preparing for the recycling.
Kind: instance method of Component
component.onRecycle()
Lifecycle method. Called when the component is recycled and reused between renders.
A component is recycled when:
- It has a
keyand a previous child of the same class with the same key exists - It doesn't have a
keybut has the same type and position in the template or partial
During recycling, the component instance is reused and its props are updated with new values. The component's element may be moved in the DOM if the new template structure differs from the previous one.
Kind: instance method of Component
component.onBeforeUpdate()
Lifecycle method. Called before the component is updated or re-rendered.
This method is called at the beginning of the render method when the component's state, model, or props change and trigger a re-render.
Use this method to perform operations that need to happen before the component is updated,
such as saving previous state or preparing for the update.
Kind: instance method of Component
component.onUpdate()
Lifecycle method. Called when the component is updated or re-rendered. This method is called when the component's state, model, or props change and trigger a re-render. Use this method to perform operations that need to happen on every update.
Kind: instance method of Component
component.onDestroy(…args)
Lifecycle method. Called when the component is destroyed.
Use this method to clean up resources, cancel timers, remove event listeners, etc.
It also runs for a child built in an expression (Child.mount(options) or
new Child(options)) that the parent's render discards because it recycles the
previous one (see render).
Kind: instance method of Component
| Param | Type | Description |
|---|---|---|
| …args | \* |
Options object or any arguments passed to destroy method. |
Component.markAsSafeHTML(value) ⇒ object
Mark a string as safe HTML to be rendered. Normally you don't need to use this method, as Rasti will automatically mark string literals as safe HTML when the component is created and when using the Component.partial method. Be sure that the string is safe to be rendered, as it will be inserted into the DOM without any sanitization.
Kind: static method of Component
Returns: object - An opaque safe HTML value.
| Param | Type |
|---|---|
| value | string |
Component.extend(object)
Helper method used to extend a Component, creating a subclass.
Kind: static method of Component
| Param | Type | Description |
|---|---|---|
| object | object | function |
Object containing methods to be added to the new Component subclass. Also can be a function that receives the parent prototype and returns an object. |
Component.mount([options], [containerEl], [shouldHydrateExistingDOM]) ⇒ Component
Mount the component into the DOM. Creates a new component instance with the provided options and optionally mounts it into the DOM.
Mounting modes:
- Normal mount (default): Renders the component as HTML and appends it to the provided element. Use this for client-side rendering.
- Hydration mode: Assumes the DOM already contains the component's HTML (from server-side rendering).
If containerEl is not provided, the component is instantiated but not mounted (the same as using new Component(options)). You can mount it later by calling render() and appending the element (this.el) to the DOM.
Kind: static method of Component
Returns: Component - The component instance.
| Param | Type | Default | Description |
|---|---|---|---|
| [options] | object |
{} |
The component options. These will be passed to the constructor and can include model, state, props, lifecycle methods, and any other component-specific options. |
| [containerEl] | node |
The DOM element where the component will be mounted. If provided, the component will be rendered and appended to this element. If not provided, the component is created but not mounted. A component that has its own el (an option, a class field, or a function that returns it) hydrates onto that element instead, as render() does, and the container is not used. | |
| [shouldHydrateExistingDOM] | boolean |
false |
If true, enables hydration mode for server-side rendering. The component will assume the DOM already contains its HTML structure and will only hydrate it. If false (default), the component will be rendered from scratch and appended to containerEl. |
Example
import { Component, Model } from 'rasti';
const Button = Component.create`
<button class="${({ props }) => props.className}">
${({ props }) => props.label}
</button>
`;
// Normal mount: render and append to DOM.
const button = Button.mount({
label: 'Click me'
}, document.body);
// Create without mounting (mount later).
const button2 = Button.mount({ className : 'secondary', label : 'Save' });
// Later, render and append it to the DOM.
document.body.appendChild(button2.render().el);
// Hydration mode: hydrate existing server-rendered HTML
// Assuming document.body already contains the HTML structure of the button.
const hydratedButton = Button.mount({
className : 'primary',
label : 'Click me'
}, document.body, true);
Component.create(strings, …expressions) ⇒ Component
Takes a template function, or a tagged template string, and returns a new Component class. Both are sugar for defining the component's template method. A component with methods, state or several hooks reads better as a subclass that defines template() itself; create suits presentational components.
- Template function: the function is used as
template()itself, so it re-runs on every render and interpolates plain values. It is called with the component as its argument, so an arrow function destructures what it uses, and afunctionreadsthis. It returns a partial, or a component to contain.
const Button = Component.create(({ props, html }) => html`
<button class="${props.className}">
${props.renderChildren()}
</button>
`);
- Tagged template: the template becomes the component's root partial, and its outer
element becomes
this.el. Its interpolations are defined once, with the declaration, so anything dynamic must be a function: it is called on every render, bound to the component and receiving it as its argument. That pays off in a few specific cases. A function that returnsnull,undefined,falseor an empty string renders nothing.
const Row = Component.create`
<tr class="${({ props }) => props.selected ? 'selected' : ''}">
<td>${({ model }) => model.label}</td>
<td><a onClick=${function() { this.props.handleRemove(this.model); }}>Remove</a></td>
</tr>
`;
- Attributes: a quoted value that is a function is called and its result used; an unquoted one is passed as it is. A boolean decides whether the attribute is present.
const Input = Component.create(({ props, html }) => html`
<input type="text" disabled="${props.disabled}" />
`);
- Event handlers: camel-cased
on*attributes bind a function, or a string naming a method of the component. The handler runs withthisbound to the component and receives(event, component, matched),matchedbeing the element that carries the attribute. Handlers are not bound to the elements: one listener per event type is delegated to the component's root element and looks the handler up on each event, so a handler created anew on every render touches no DOM. On a component tag, an attribute is an option for the child, not a listener: name callback propshandle*, since lifecycle hook names such asonChangeare options the component takes for itself.
const Counter = Component.create(({ model, html }) => html`
<div>
<span>${model.count}</span>
<button onClick=${() => model.count++}>+</button>
<button onClick="reset">Reset</button>
</div>
`).extend({
reset() {
this.model.count = 0;
}
});
If you need custom delegation (e.g., {'click .selector': 'handler'}),
you may override the events property as described in View.delegateEvents.
- Child components are written as tags: attributes become props, and the content
between the tags becomes
props.renderChildren. In a list, give each one akey, so it is reused and moved instead of built again on every update.
const Navigation = Component.create(({ props, html }) => html`
<nav>
${props.items.map(item => html`
<${Button} key="${item.id}" className="nav">${item.label}</${Button}>
`)}
</nav>
`);
- Containers: a template that is a single component makes the component a
container:
this.elis the child's element, with no wrapper around it.
const ButtonOk = Component.create`
<${Button} className="ok">Ok</${Button}>
`;
const ButtonCancel = Component.create(({ html }) => html`
<${Button} className="cancel">Cancel</${Button}>
`);
The function may also return a component it builds (Button.mount(options)), which is
then built on every render (see render).
- Called on a subclass, the new component extends it, so the template can use its methods.
class ListBase extends Component {
renderItems() {
return this.props.items.map(item => this.html`<li>${item}</li>`);
}
}
const List = ListBase.create`
<ul>${(self) => self.renderItems()}</ul>
`;
Kind: static method of Component
Returns: Component - The newly created component class.
| Param | Type | Description |
|---|---|---|
| strings | function | string |
A template function that returns a partial or a child component, or a tagged template string for the component. |
| …expressions | \* |
The expressions to be interpolated within the template. |
Emitter
Emitter is a class that provides an easy way to implement the observer pattern
in your applications.
It can be extended to create new classes that have the ability to emit and bind custom named events.
Emitter is used by Model and View classes, which inherit from it to implement
event-driven functionality.
Inverse of Control Pattern
The Emitter class includes "inverse of control" methods (listenTo, listenToOnce, stopListening)
that allow an object to manage its own listening relationships. Instead of:
// Traditional approach - harder to clean up
otherObject.on('change', this.myHandler);
otherObject.on('destroy', this.cleanup);
// Later you need to remember to clean up each listener
otherObject.off('change', this.myHandler);
otherObject.off('destroy', this.cleanup);
You can use:
// Inverse of control - easier cleanup
this.listenTo(otherObject, 'change', this.myHandler);
this.listenTo(otherObject, 'destroy', this.cleanup);
// Later, clean up ALL listeners at once
this.stopListening(); // Removes all listening relationships
This pattern is particularly useful for preventing memory leaks and simplifying cleanup in component lifecycle management.
Example
import { Emitter } from 'rasti';
// Custom cart
class ShoppingCart extends Emitter {
constructor() {
super();
this.items = [];
}
addItem(item) {
this.items.push(item);
// Emit a custom event called `itemAdded`.
// Pass the added item as an argument to the event listener.
this.emit('itemAdded', item);
}
}
// Create an instance of ShoppingCart and Logger
const cart = new ShoppingCart();
// Listen to the `itemAdded` event and log the added item using the logger.
cart.on('itemAdded', (item) => {
console.log(`Item added to cart: ${item.name} - Price: $${item.price}`);
});
// Simulate adding items to the cart
const item1 = { name : 'Smartphone', price : 1000 };
const item2 = { name : 'Headphones', price : 150 };
cart.addItem(item1); // Output: "Item added to cart: Smartphone - Price: $1000"
cart.addItem(item2); // Output: "Item added to cart: Headphones - Price: $150"
emitter.on(type, listener) ⇒ function
Adds event listener.
Kind: instance method of Emitter
Returns: function - A function to remove the listener.
| Param | Type | Description |
|---|---|---|
| type | string |
Type of the event (e.g. change). |
| listener | function |
Callback function to be called when the event is emitted. |
Example
// Re render when model changes.
this.model.on('change', this.render.bind(this));
emitter.once(type, listener) ⇒ function
Adds event listener that executes once.
Kind: instance method of Emitter
Returns: function - A function to remove the listener.
| Param | Type | Description |
|---|---|---|
| type | string |
Type of the event (e.g. change). |
| listener | function |
Callback function to be called when the event is emitted. |
Example
// Log a message once when model changes.
this.model.once('change', () => console.log('This will happen once'));
emitter.off([type], [listener])
Removes event listeners with flexible parameter combinations.
Kind: instance method of Emitter
| Param | Type | Description |
|---|---|---|
| [type] | string |
Type of the event (e.g. change). If not provided, removes ALL listeners from this emitter. |
| [listener] | function |
Specific callback function to remove. If not provided, removes all listeners for the specified type. Behavior based on parameters: - off() - Removes ALL listeners from this emitter - off(type) - Removes all listeners for the specified event type - off(type, listener) - Removes the specific listener for the specified event type |
Example
// Remove all listeners from this emitter
this.model.off();
Example
// Remove all 'change' event listeners
this.model.off('change');
Example
// Remove specific listener for 'change' events
const myListener = () => console.log('changed');
this.model.on('change', myListener);
this.model.off('change', myListener);
emitter.emit(type, […args])
Emits event of specified type. Listeners will receive specified arguments.
Kind: instance method of Emitter
| Param | Type | Description |
|---|---|---|
| type | string |
Type of the event (e.g. change). |
| […args] | any |
Optional arguments to be passed to listeners. |
Example
// Emit validation error event with no arguments
this.emit('invalid');
Example
// Emit change event with data
this.emit('change', { field : 'name', value : 'John' });
emitter.listenTo(emitter, type, listener) ⇒ function
Listen to an event of another emitter (Inverse of Control pattern).
This method allows this object to manage its own listening relationships,
making cleanup easier and preventing memory leaks. Instead of calling
otherEmitter.on(), you call this.listenTo(otherEmitter, ...) which
allows this object to track and clean up all its listeners at once.
Kind: instance method of Emitter
Returns: function - A function to stop listening to the event.
| Param | Type | Description |
|---|---|---|
| emitter | Emitter |
The emitter to listen to. |
| type | string |
The type of the event to listen to. |
| listener | function |
The listener to call when the event is emitted. |
Example
// Instead of: otherModel.on('change', this.render.bind(this));
// Use: this.listenTo(otherModel, 'change', this.render.bind(this));
// This way you can later call this.stopListening() to clean up all listeners
emitter.listenToOnce(emitter, type, listener) ⇒ function
Listen to an event of another emitter and remove the listener after it is called (Inverse of Control pattern).
Similar to listenTo() but automatically removes the listener after the first execution,
like once() but with the inverse of control benefits for cleanup management.
Kind: instance method of Emitter
Returns: function - A function to stop listening to the event.
| Param | Type | Description |
|---|---|---|
| emitter | Emitter |
The emitter to listen to. |
| type | string |
The type of the event to listen to. |
| listener | function |
The listener to call when the event is emitted. |
Example
// Listen once to another emitter's initialization event
this.listenToOnce(otherModel, 'initialized', () => {
console.log('Other model initialized');
});
emitter.stopListening([emitter], [type], [listener])
Stop listening to events from other emitters (Inverse of Control pattern).
This method provides flexible cleanup of listening relationships established with listenTo().
All parameters are optional, allowing different levels of cleanup granularity.
Kind: instance method of Emitter
| Param | Type | Description |
|---|---|---|
| [emitter] | Emitter |
The emitter to stop listening to. If not provided, stops listening to ALL emitters. |
| [type] | string |
The type of event to stop listening to. If not provided, stops listening to all event types from the specified emitter. |
| [listener] | function |
The specific listener to remove. If not provided, removes all listeners for the specified event type from the specified emitter. Behavior based on parameters: - stopListening() - Stops listening to ALL events from ALL emitters - stopListening(emitter) - Stops listening to all events from the specified emitter - stopListening(emitter, type) - Stops listening to the specified event type from the specified emitter - stopListening(emitter, type, listener) - Stops listening to the specific listener for the specific event from the specific emitter |
Example
// Stop listening to all events from all emitters (complete cleanup)
this.stopListening();
Example
// Stop listening to all events from a specific emitter
this.stopListening(otherModel);
Example
// Stop listening to 'change' events from a specific emitter
this.stopListening(otherModel, 'change');
Example
// Stop listening to a specific listener
const myListener = () => console.log('changed');
this.listenTo(otherModel, 'change', myListener);
this.stopListening(otherModel, 'change', myListener);
Model ⇐ Emitter
- Orchestrates data and business logic.
- Emits events when data changes.
A Model manages an internal table of data attributes and triggers change events when any of its data is modified.
Models may handle syncing data with a persistence layer. To design your models, create atomic, reusable objects
that contain all the necessary functions for manipulating their specific data.
Models should be easily passed throughout your app and used anywhere the corresponding data is needed.
Construction Flow
preinitialize()is called with all constructor argumentsthis.defaultsare resolved (if function, it's called and bound to the model)parse()is called with all constructor arguments to process the datathis.attributesis built by merging defaults and parsed data- Getters/setters are generated for each attribute to emit change events
Extends: Emitter
| Param | Type | Default | Description |
|---|---|---|---|
| [attributes] | object |
{} |
Primary data object containing model attributes |
| […args] | \* |
Additional arguments passed to preinitialize and parse methods |
Properties
| Name | Type | Description |
|---|---|---|
| defaults | object | function |
Default attributes for the model. If a function, it's called bound to the model instance to get defaults. |
| previous | object |
Object containing previous attributes when a change occurs. |
Example
import { Model } from 'rasti';
// User model
class User extends Model {
preinitialize() {
this.defaults = { name : '', email : '', role : 'user' };
}
}
// Order model with nested User and custom methods
class Order extends Model {
preinitialize(attributes, options = {}) {
this.defaults = {
id : null,
total : 0,
status : 'pending',
user : null
};
this.apiUrl = options.apiUrl || '/api/orders';
}
parse(data, options = {}) {
const parsed = { ...data };
// Convert user object to User model instance
if (data.user && !(data.user instanceof User)) {
parsed.user = new User(data.user);
}
return parsed;
}
toJSON() {
const result = {};
for (const [key, value] of Object.entries(this.attributes)) {
if (value instanceof Model) {
result[key] = value.toJSON();
} else {
result[key] = value;
}
}
return result;
}
async fetch() {
try {
const response = await fetch(`${this.apiUrl}/${this.id}`);
const data = await response.json();
// Parse the fetched data and update model
const parsed = this.parse(data);
this.set(parsed, { source : 'fetch' });
return this;
} catch (error) {
console.error('Failed to fetch order:', error);
throw error;
}
}
}
// Create order with nested user data
const order = new Order({
id : 123,
total : 99.99,
user : { name : 'Alice', email : 'alice@example.com' }
});
console.log(order.user instanceof User); // true
// Serialize with nested models
const json = order.toJSON();
console.log(json); // { id: 123, total: 99.99, status: 'pending', user: { name: 'Alice', email: 'alice@example.com', role: 'user' } }
// Listen to fetch updates
order.on('change', (model, changed, options) => {
if (options?.source === 'fetch') {
console.log('Order updated from server:', changed);
}
});
// Fetch latest data from server
await order.fetch();
- Model ⇐
Emitter- instance
- .preinitialize([attributes], […args])
- .defineAttribute(key)
- .get(key) ⇒
any - .set(key, [value], […args]) ⇒
Model - .parse([data], […args]) ⇒
object - .toJSON() ⇒
object
- static
- .attributePrefix :
string
- .attributePrefix :
- instance
model.preinitialize([attributes], […args])
Called before any instantiation logic runs for the Model.
Receives all constructor arguments, allowing for flexible initialization patterns.
Use this to set up defaults, configure the model, or handle custom constructor arguments.
Kind: instance method of Model
| Param | Type | Default | Description |
|---|---|---|---|
| [attributes] | object |
{} |
Primary data object containing model attributes |
| […args] | \* |
Additional arguments passed from the constructor |
Example
class User extends Model {
preinitialize(attributes, options = {}) {
this.defaults = { name : '', role : options.defaultRole || 'user' };
this.apiEndpoint = options.apiEndpoint || '/users';
}
}
const user = new User({ name : 'Alice' }, { defaultRole : 'admin', apiEndpoint : '/api/users' });
model.defineAttribute(key)
Generate getter/setter for the given attribute key to emit change events.
The property name uses attributePrefix + key (e.g., with prefix 'attr', key 'name' becomes 'attrname').
Called internally by the constructor for each key in this.attributes.
Override with an empty method if you don't want automatic getters/setters.
The accessors are generated once for each class and set of attributes, on a prototype shared by every model holding them, so they are inherited rather than own properties of the model. A class shares them for up to 256 sets; a model holding any other set gets a prototype of its own.
Kind: instance method of Model
| Param | Type | Description |
|---|---|---|
| key | string |
Attribute key from this.attributes |
Example
// Custom prefix for all attributes
class PrefixedModel extends Model {
static attributePrefix = 'attr_';
}
const model = new PrefixedModel({ name: 'Alice' });
console.log(model.attr_name); // 'Alice'
// Disable automatic getters/setters
class ManualModel extends Model {
defineAttribute() {
// Empty - no getters/setters generated
}
getName() {
return this.get('name'); // Manual getter
}
}
model.get(key) ⇒ any
Get an attribute from this.attributes.
This method is called internally by generated getters.
Kind: instance method of Model
Returns: any - The attribute value.
| Param | Type | Description |
|---|---|---|
| key | string |
Attribute key. |
model.set(key, [value], […args]) ⇒ Model
Set one or more attributes into this.attributes and emit change events.
Supports two call signatures: set(key, value, ...args) or set(object, ...args).
Additional arguments are passed to change event listeners, enabling custom behavior.
A set called from a change:attribute listener joins the change event of the
set that triggered it: that event is emitted once, after every change:attribute,
with all the attributes changed in between and the arguments of the first set.
A set called from a change listener emits a change event of its own.
Kind: instance method of Model
Returns: Model - This model instance for chaining
Emits: change Emitted when any attribute changes. Listeners receive `(model, changedAttributes, ...event:args)`, change:attribute Emitted for each changed attribute. Listeners receive `(model, newValue, ...event:args)`
| Param | Type | Description |
|---|---|---|
| key | string | object |
Attribute key (string) or object containing key-value pairs |
| [value] | \* |
Attribute value (when key is string) |
| […args] | \* |
Additional arguments passed to event listeners |
Example
// Basic usage
model.set('name', 'Alice');
model.set({ name : 'Alice', age : 30 });
// With options for listeners
model.set('name', 'Bob', { silent : false, validate : true });
model.on('change:name', (model, value, options) => {
if (options?.validate) {
// Custom validation logic
}
});
model.parse([data], […args]) ⇒ object
Transforms and validates data before it becomes model attributes. Called during construction with all constructor arguments, allowing flexible data processing. Override this method to transform incoming data, create nested models, or handle different data formats.
Kind: instance method of Model
Returns: object - Processed data that will become the model's attributes
| Param | Type | Default | Description |
|---|---|---|---|
| [data] | object |
{} |
Primary data object to be parsed into attributes |
| […args] | \* |
Additional arguments from constructor, useful for parsing options |
Example
// Transform nested objects into models
class User extends Model {}
class Order extends Model {
parse(data, options = {}) {
// Skip parsing if requested
if (options.raw) return data;
// Transform user data into User model
const parsed = { ...data };
if (data.user && !(data.user instanceof User)) {
parsed.user = new User(data.user);
}
return parsed;
}
}
// Usage with parsing options
const order1 = new Order({ id : 1, user : { name : 'Alice' } }); // user becomes User model
const order2 = new Order({ id : 2, user : { name : 'Bob' } }, { raw : true }); // user stays plain object
model.toJSON() ⇒ object
Return object representation of the model to be used for JSON serialization.
By default returns a copy of this.attributes.
You can override this method to customize serialization behavior, such as calling toJSON recursively on nested Model instances.
Kind: instance method of Model
Returns: object - Object representation of the model to be used for JSON serialization.
Example
// Basic usage - returns a copy of model attributes:
const user = new Model({ name : 'Alice', age : 30 });
const json = user.toJSON();
console.log(json); // { name : 'Alice', age : 30 }
// Override toJSON for recursive serialization of nested models:
class User extends Model {}
class Order extends Model {
parse(data) {
// Ensure user is always a User model
return { ...data, user : data.user instanceof User ? data.user : new User(data.user) };
}
toJSON() {
const result = {};
for (const [key, value] of Object.entries(this.attributes)) {
if (value instanceof Model) {
result[key] = value.toJSON();
} else {
result[key] = value;
}
}
return result;
}
}
const order = new Order({ id : 1, user : { name : 'Alice' } });
const json = order.toJSON();
console.log(json); // { id : 1, user : { name : 'Alice' } }
Model.attributePrefix : string
Static property that defines a prefix for generated getters/setters. When set, all attribute properties will be prefixed (e.g., 'attr_name' instead of 'name'). Useful for avoiding naming conflicts or creating a consistent property naming convention.
Kind: static property of Model
Default: "''"
Example
// Set prefix for all models of this class
class ApiModel extends Model {
static attributePrefix = 'attr_';
}
const user = new ApiModel({ name : 'Alice', email : 'alice@example.com' });
console.log(user.attr_name); // 'Alice'
console.log(user.attr_email); // 'alice@example.com'
// Still access via get/set methods without prefix
console.log(user.get('name')); // 'Alice'
user.set('name', 'Bob');
console.log(user.attr_name); // 'Bob'
View ⇐ Emitter
- Listens for changes and renders the UI.
- Handles user input and interactivity.
- Sends captured input to the model.
A View is an atomic unit of the user interface that can render data from a specific model or multiple models.
However, views can also be independent and have no associated data.
Models must be unaware of views. Views, on the other hand, may render model data and listen to the change events
emitted by the models to re-render themselves based on changes.
Each View has a root element, this.el, which is used for event delegation.
All element lookups are scoped to this element, and any rendering or DOM manipulations should be done inside it.
If this.el is not present, an element will be created using this.tag (defaulting to div) and this.attributes.
Extends: Emitter
| Param | Type | Description |
|---|---|---|
| options | object |
Object containing options. The following keys will be merged into the view instance: el, tag, attributes, events, model, template, onDestroy. |
Properties
| Name | Type | Description |
|---|---|---|
| el | node | function |
Every view has a root DOM element stored at this.el. If not present, it will be created. If this.el is a function, it will be called to get the element at this.ensureElement, bound to the view instance. See View.ensureElement. |
| tag | string | function |
If this.el is not present, an element will be created using this.tag and this.attributes. Default is div. If it is a function, it will be called to get the tag, bound to the view instance. See View.ensureElement. |
| attributes | object | function |
If this.el is not present, an element will be created using this.tag and this.attributes. If it is a function, it will be called to get the attributes object, bound to the view instance. See View.ensureElement. |
| events | object | function |
Object in the format {'event selector' : 'listener'}. It will be used to bind delegated event listeners to the root element. If it is a function, it will be called to get the events object, bound to the view instance. See View.delegateEvents. |
| model | object |
A model or any object containing data and business logic. |
| template | function |
A function that returns a string with the view's inner HTML. See View.render. |
| children | Array.<View> |
Child views, added with addChild and destroyed with the view. |
| parent | View | null |
The view that adopted this one with addChild. null before that, for a view mounted at the root, and after destroy. For a component's slotted content it is the component that renders it, not the one whose template wrote it. |
| uid | string |
Unique identifier for the view instance. This can be used to generate unique IDs for elements within the view. It is automatically generated and should not be set manually. |
Example
import { View, Model } from 'rasti';
class Timer extends View {
constructor(options) {
super(options);
// Create model to store internal state. Set `seconds` attribute to 0.
this.model = new Model({ seconds : 0 });
// Listen to changes in model `seconds` attribute and re-render.
this.model.on('change:seconds', this.render.bind(this));
// Increment model `seconds` attribute every 1000 milliseconds.
this.interval = setInterval(() => this.model.seconds++, 1000);
}
template(model) {
return `Seconds: <span>${View.sanitize(model.seconds)}</span>`;
}
render() {
if (this.template) {
this.el.innerHTML = this.template(this.model);
}
return this;
}
}
// Render view and append view's element into the body.
document.body.appendChild(new Timer().render().el);
- View ⇐
Emitter- instance
- .preinitialize(options)
- .$(selector) ⇒
node - .$$(selector) ⇒
Array.<node> - .destroy(options) ⇒
View - .onDestroy(options)
- .addChild(child) ⇒
View - .destroyChildren()
- .ensureUid()
- .ensureElement()
- .createElement(tag, attributes) ⇒
node - .removeElement() ⇒
View - .delegateEvents([events]) ⇒
View - .undelegateEvents() ⇒
View - .render() ⇒
View
- static
- .uid :
number - .sanitize(value) ⇒
string - .resetUid()
- .uid :
- instance
view.preinitialize(options)
If you define a preinitialize method, it will be invoked when the view is first created, before any instantiation logic is run.
Kind: instance method of View
| Param | Type | Description |
|---|---|---|
| options | object |
The view options. |
view.$(selector) ⇒ node
Returns the first element that matches the selector,
scoped to DOM elements within the current view's root element (this.el).
Kind: instance method of View
Returns: node - Element matching selector within the view's root element (this.el).
| Param | Type | Description |
|---|---|---|
| selector | string |
CSS selector. |
view.$$(selector) ⇒ Array.<node>
Returns a list of elements that match the selector,
scoped to DOM elements within the current view's root element (this.el).
Kind: instance method of View
Returns: Array.<node> - List of elements matching selector within the view's root element (this.el).
| Param | Type | Description |
|---|---|---|
| selector | string |
CSS selector. |
view.destroy(options) ⇒ View
Destroy the view.
Destroy children views if any, undelegate events, stop listening to events, call onDestroy lifecycle method.
Kind: instance method of View
Returns: View - Return this for chaining.
| Param | Type | Description |
|---|---|---|
| options | object |
Options object or any arguments passed to destroy method will be passed to onDestroy method. |
view.onDestroy(options)
onDestroy lifecycle method is called after the view is destroyed.
Override with your code. Useful to stop listening to model's events.
Kind: instance method of View
| Param | Type | Description |
|---|---|---|
| options | object |
Options object or any arguments passed to destroy method. |
view.addChild(child) ⇒ View
Add a view as a child.
Children views are stored at this.children, and destroyed when the parent is destroyed.
Sets the child's parent to this view.
Returns the child for chaining.
Kind: instance method of View
| Param | Type |
|---|---|
| child | View |
view.destroyChildren()
Call destroy method on children views.
Kind: instance method of View
view.ensureUid()
Ensure that the view has a unique id at this.uid.
Kind: instance method of View
view.ensureElement()
Ensure that the view has a root element at this.el.
You shouldn't call this method directly. It's called from the constructor.
You may override it if you want to use a different logic or to
postpone element creation.
Kind: instance method of View
view.createElement(tag, attributes) ⇒ node
Create an element.
Called from the constructor if this.el is undefined, to ensure
the view has a root element.
Kind: instance method of View
Returns: node - The created element.
| Param | Type | Default | Description |
|---|---|---|---|
| tag | string |
"div" |
Tag for the element. Default to div |
| attributes | object |
Attributes for the element. |
view.removeElement() ⇒ View
Remove this.el from the DOM.
Kind: instance method of View
Returns: View - Return this for chaining.
view.delegateEvents([events]) ⇒ View
Provide declarative listeners for DOM events within a view. If an events object is not provided,
it defaults to using this.events. If this.events is a function, it will be called to get the events object.
The events object should follow the format {'event selector': 'listener'}:
event: The type of event (e.g., 'click').selector: A CSS selector to match the event target. If omitted, the event is bound to the root element.listener: A function or a string representing a method name on the view. The method will be called withthisbound to the view instance.
By default, delegateEvents is called within the View's constructor. If you have a simple events object,
all of your DOM events will be connected automatically, and you will not need to call this function manually.
All attached listeners are bound to the view, ensuring that this refers to the view object when the listeners are invoked.
When delegateEvents is called again, possibly with a different events object, all previous listeners are removed and delegated afresh.
Listener signature: (event, view, matched)
event: The native DOM event object.view: The current view instance (this).matched: The element that satisfies the selector. If no selector is provided, it will be the view's root element (this.el).
If more than one ancestor between event.target and the view's root element matches the selector, the listener will be
invoked once for each matched element (from inner to outer).
The ancestors are read when the event reaches the root element, before any listener runs. A listener that re-renders or removes nodes between the target and the root does not stop the others: the nodes it took out of the view are skipped, and the walk goes on through the ones left, up to the root.
An event that does not bubble (focus, blur, mouseenter, load, scroll…) is matched against its target
alone, as it would be by a listener on that element. It is caught on its way down to the target, so its listener runs
before any listener on the target itself, and a stopPropagation() in it keeps the event from them. When views
nested in each other both match the target, the outer one runs first.
Kind: instance method of View
Returns: View - Returns this for chaining.
| Param | Type | Description |
|---|---|---|
| [events] | object |
Object in the format {'event selector' : 'listener'}. Used to bind delegated event listeners to the root element. |
Example
// Using prototype (recommended for static events)
class Modal extends View {
onClickOk(event, view, matched) {
// matched === the button.ok element that was clicked
this.close();
}
onClickCancel() {
this.destroy();
}
}
Modal.prototype.events = {
'click button.ok': 'onClickOk',
'click button.cancel': 'onClickCancel',
'submit form': 'onSubmit'
};
// Using a function for dynamic events
class DynamicView extends View {
events() {
return {
[`click .${this.model.buttonClass}`]: 'onButtonClick',
'click': 'onRootClick'
};
}
}
view.undelegateEvents() ⇒ View
Removes all of the view's delegated events.
Useful if you want to disable or remove a view from the DOM temporarily.
Called automatically when the view is destroyed and when delegateEvents is called again.
Kind: instance method of View
Returns: View - Return this for chaining.
view.render() ⇒ View
render is the core function that your view should override, in order to populate its element (this.el), with the appropriate HTML. The convention is for render to always return this.
Views are low-level building blocks for creating user interfaces. For most use cases, we recommend using Component instead, which provides a more declarative template syntax, automatic DOM updates, and a more efficient render pipeline.
If you add any child views, you should call this.destroyChildren before re-rendering.
Kind: instance method of View
Returns: View - Returns this for chaining.
Example
class UserView extends View {
render() {
if (this.template) {
const model = this.model;
// Sanitize model attributes to prevent XSS attacks.
const safeData = {
name : View.sanitize(model.name),
email : View.sanitize(model.email),
bio : View.sanitize(model.bio)
};
this.el.innerHTML = this.template(safeData);
}
return this;
}
}
View.uid : number
Counter for generating unique IDs for view instances.
This is primarily used to assign unique identifiers to each view instance (this.uid), which can be helpful for tasks like
generating element IDs.
Components use this.uid to generate data attributes for their elements, to be looked up on hydration.
For server-side rendering, this counter should be reset to 0 on every request to ensure that the generated
unique IDs match those on the client, enabling seamless hydration of components.
Kind: static property of View
Default: 0
View.sanitize(value) ⇒ string
Escape HTML entities in a string. Use this method to sanitize user-generated content before inserting it into the DOM. Override this method to provide a custom escape function. This method is inherited by Component and used to escape template interpolations.
Kind: static method of View
Returns: string - Escaped string.
| Param | Type | Description |
|---|---|---|
| value | string |
String to escape. |
View.resetUid()
Reset the unique ID counter to 0. This is useful for server-side rendering scenarios where you want to ensure that the generated unique IDs match those on the client, enabling seamless hydration of components. This method is inherited by Component.
Kind: static method of View
ComponentPartial : object
An opaque partial template produced by component.partial. It carries a template's structure and current expressions so the render engine can patch it in place.
Kind: global typedef