Context System
Understand WildflowerJS's internal context management system for DOM binding, actions, conditionals, and lists.
data-bind="username" to an element, WildflowerJS creates a binding context that knows: which element to update, which state property to watch, and how to render the value. This context is then registered so that when state.username changes, the framework can look up all contexts watching that path and update their elements directly.
Each context also tracks its position in the DOM hierarchy—its parent context and child contexts—enabling the framework to understand relationships without virtualizing the entire DOM tree. This includes relationships between bound elements within a component, between parent and child components, and between lists and their rendered items (including nested lists within list items).
Context Registry Overview
WildflowerJS maintains a ContextRegistry that manages all DOM element contexts:
| Context Type | Attribute | Purpose | Registry |
|---|---|---|---|
| Binding | data-bind |
Display reactive data | _bindings |
| Action | data-action |
Handle events | _actions |
| Conditional | data-show, data-render |
Conditional visibility (data-show) or full mount/unmount (data-render) |
_conditionals |
| List | data-list |
Array rendering | _lists |
| Model | data-model |
Two-way binding | _models |
data-* attributes also support a data-wf-* prefix (e.g., data-wf-bind, data-wf-action). Use the wf prefix when integrating with third-party libraries that may conflict with standard data-* attributes. Both prefixes are functionally identical.
Context Lifecycle
Each context goes through a predictable lifecycle with three phases:
1. Creation
When the framework scans the DOM (during component initialization or after dynamic content is added), it discovers elements with reactive attributes and creates the appropriate context for each:
data-bind="username"→ Creates a binding context that will update this element whenstate.usernamechangesdata-action="save"→ Creates an action context that will call thesave()method when clickeddata-list="items"→ Creates a list context that manages rendering items from the arraydata-show="isVisible"→ Creates a conditional context that controls element visibilitydata-model="email"→ Creates a model context for two-way binding with form inputs
Each context is registered in the framework's context registry, indexed by type, element, and component for efficient lookup.
2. Active Phase
Once created, contexts actively respond to changes:
- Binding contexts listen for state changes on their watched path and update the DOM element's content
- Action contexts listen for DOM events (click, input, etc.) and invoke the appropriate component method
- List contexts detect array mutations (push, splice, etc.) and efficiently update only the affected DOM elements
- Conditional contexts evaluate their condition when dependent state changes and show/hide the element
- Model contexts synchronize in both directions: DOM changes update state, state changes update the DOM
The framework tracks dependencies between contexts, so when state.username changes, only the contexts watching that specific path are notified, not every context in the application.
3. Destruction
Contexts are cleaned up when their associated DOM element is removed:
- Component destruction: when a component is destroyed, all its contexts are removed from the registry
- List item removal: when an item is removed from a list, all contexts for that item's DOM elements are destroyed
- Dynamic content replacement: when
innerHTMLreplaces content, orphaned contexts are garbage collected
The framework runs periodic garbage collection to detect and clean up contexts whose DOM elements are no longer in the document, preventing memory leaks.
data-show keeps contexts alive when hiding elements; it only toggles CSS visibility. This is more efficient for frequently toggled content since contexts don't need to be recreated. For content that should fully unmount (destroying contexts), use data-render instead.
Cross-Entity Communication
For HTML template bindings, use the $ universal accessor to read state from any entity directly: data-bind="$component.path". For JavaScript-level access, use subscribe with this.stores for stores, or wildflower.getComponent() for components:
<!-- HTML: bind directly to another entity's state -->
<span data-bind="$user-session.user.name"></span>
<div data-show="$auth.isLoggedIn">Welcome!</div>
<span data-bind="$cart.itemCount"></span>
// JavaScript: use subscribe + this.stores for store access
wildflower.component('cart-badge', {
subscribe: {
cart: ['items']
},
computed: {
itemCount() {
return this.stores.cart.items.length
}
}
})
// JavaScript: use getComponent() for component access
wildflower.component('themed-panel', {
computed: {
themeClass() {
const theme = wildflower.getComponent('theme-manager')
return theme ? 'theme-' + theme.mode : 'theme-light'
}
}
})
Dependency Tracking
The context system automatically tracks dependencies between components:
- Components using
subscribeor$entity.pathbindings automatically register as dependents - Changes trigger updates only in dependent components
- Circular dependency detection prevents infinite loops
- Cleanup occurs automatically when components are destroyed
Dependency Maps
WildflowerJS maintains internal dependency maps to track cross-entity relationships:
// Entity dependency tracking (store/plugin subscribers)
_entityDependents: Map() // entityId → Set of dependent component IDs
// Subscribe block example
wildflower.component('dashboard', {
subscribe: { cart: ['items'] },
// This creates a dependency: dashboard depends on cart store's items path
})
Context Performance
Understanding context performance characteristics:
| Operation | Characteristic | Notes |
|---|---|---|
| Context Creation | Fast | WeakMap-based registration |
| Binding Update | Direct | Updates DOM element immediately |
| Dependency Resolution | Fast | Map-based lookups |
| Context Cleanup | Scales with dependencies | Cleans up all registered dependencies |
| Entity Lookup | Fast | Map-based entity lookup |
Advanced Context Patterns
Context Debugging
Debugging context-related issues:
// Enable context debugging
wildflower.debug = true
// Access context registry
const registry = wildflower.contextRegistry
// Inspect specific context types
console.log('Bindings:', registry._bindings.size)
console.log('Actions:', registry._actions.size)
console.log('Conditionals:', registry._conditionals.size)
// Check component dependencies
const componentId = this.componentId
console.log('Dependencies:', registry._dependingComponents.get(componentId))
Inspecting Context Hierarchy
You can inspect the context hierarchy at runtime using the context registry:
// Get a summary of all registered contexts by type
const registry = wildflower.contextRegistry
console.log('Contexts by type:', registry.contextsByType)
// Inspect contexts for a specific component
console.log('Contexts by component:', registry.contextsByComponent)
This is useful for debugging binding issues. You can verify that the expected contexts exist for your elements and that they're watching the correct state paths.
Context Best Practices
✅ Do
- Use
$entity.pathin HTML for cross-entity data binding - Rely on automatic dependency tracking
- Clean up event listeners in destroy()
- Use
subscribe+this.storesfor store access in JS - Leverage the framework's context lifecycle
❌ Don't
- Manually manipulate the context registry
- Create circular dependencies between components
- Access private context properties directly
- Ignore memory leaks in store subscriptions
- Override framework context management