SPX Components
SPX components serve as a bridge between JavaScript logic and the Document Object Model (DOM), enhancing interactivity in web applications. They are defined by a unique name, associated DOM elements, state, and event bindings. The name
identifies the component within the application, while nodes
specify which DOM elements the component interacts with. The state
holds data that the component manages, which can include various data types like numbers, strings, booleans, objects, or arrays.
Hooks
SPX components incorporate three essential lifecycle callback hooks for precise control over component behavior. The connect
hook triggers at the outset and is ideal for initial setup, executing just once. The onmount
hook will trigger every time a component view is attached to the DOM, useful for logic that needs to run upon rendering. The unmount
hook is invoked each time a component’s view is detached from the DOM, this allows you to perform any necessary cleanups before component removal applies. Hooks provide you with a simple and effective management point, allowing components to responsibly handle their lifecycle, from initialization to termination and recurrence.
Events
Events are crucial for interactivity. For instance, a click event can be bound directly in HTML using <button spx@click="demo.open">
(or whatever element your event should be attached), where open
is a method defined within the component. This method receives an event object with methods like preventDefault()
to stop default browser behavior and properties like attrs
for accessing attributes passed with the event.
Markup
SPX components connect with DOM elements via attribute annotations. Initializing a component involves assigning its name to the spx-component
attribute on an HTML element. Component state is defined using state directives on the same element where the component is declared. Nodes and events can be defined anywhere in the DOM using SPX directives, allowing for dynamic attachments across different pages. This flexibility is due to SPX’s component persistence throughout a session, which means components can be referenced and interacted with even as the user navigates through different parts of the application.
To ensure SPX is aware of their existence, all components must be registered. This can be achieved either through the spx.register methods or by passing them to the components option upon connection, offering flexibility in your approach. Registered components are stored in the session and become available to SPX at runtime. However, components remain dormant until an spx-component
directive is encountered. At that point, SPX establishes an instance using the registered component. Once created, this instance persists throughout the SPX session, enduring until a hard-refresh occurs. This incremental approach ensures a structured execution flow.