đī¸ CreatorContent.net
U
User
!
-
!
-
Manage Subscription
Manage Tokens
Storage
Media Library â
Documentation
User Dashboard
Podcasts
Podcasts
Episodes
Transcriptions
Contributors
Studio
Public Profile
Public Profiles
Blog
Event Lists
Surveys
Contact Forms
Subscribers
Notifications & Shoutouts
Development
React Test
Media Library
Help Center
Admin Dashboard
Logout
Back to Documentation
Data Binding System
Data Binding System
File: data-binding-system.md
Documentation Index
Loading documentation...
# Data Binding System Documentation ## Overview The Data Binding System is a lightweight, reactive JavaScript framework that provides automatic synchronization between data and DOM elements. It eliminates the need for manual DOM manipulation and provides a clean, declarative way to build interactive user interfaces. ## Features - **Reactive Data Binding**: Automatic updates when data changes - **Form Data Binding**: Automatic form data collection and synchronization - **Table Data Binding**: Dynamic table rendering with templates - **API Integration**: Built-in API helpers with automatic data binding - **Event Subscription**: Subscribe to data changes for custom logic - **DOM Watching**: Watch DOM changes and update data automatically - **Memory Management**: Automatic cleanup of watchers and subscribers ## Core Concepts ### Data Store The system maintains a central data store where all application state is kept. Data is organized by keys and can be any JavaScript value (strings, numbers, objects, arrays, etc.). ### Subscribers Components can subscribe to data changes and automatically update when the data changes. This creates a reactive system where UI updates happen automatically. ### Watchers The system can watch DOM elements for changes and automatically update the data store when elements change. ## API Reference ### Core Methods #### `dataBinder.set(key, value)` Sets a value in the data store and notifies all subscribers. ```javascript dataBinder.set('user', { name: 'John', email: 'john@example.com' }); dataBinder.set('counter', 42); ``` #### `dataBinder.get(key)` Retrieves a value from the data store. ```javascript const user = dataBinder.get('user'); const counter = dataBinder.get('counter'); ``` #### `dataBinder.subscribe(key, callback)` Subscribes to data changes. The callback is called whenever the data changes. ```javascript dataBinder.subscribe('user', (user) => { console.log('User data changed:', user); updateUserDisplay(user); }); ``` #### `dataBinder.unsubscribe(key, callback)` Unsubscribes from data changes. ```javascript const callback = (user) => console.log('User changed:', user); dataBinder.subscribe('user', callback); // Later... dataBinder.unsubscribe('user', callback); ``` ### DOM Binding Methods #### `dataBinder.bind(key, selector, options)` Binds data to DOM elements. When the data changes, the elements are automatically updated. ```javascript // Simple text binding dataBinder.bind('userName', '#user-name'); // Attribute binding dataBinder.bind('userAvatar', '#user-avatar', { attribute: 'src' }); // Property binding dataBinder.bind('isVisible', '#user-card', { property: 'style.display' }); ``` #### `dataBinder.watch(selector, key, options)` Watches DOM elements for changes and updates the data store. ```javascript // Watch input value dataBinder.watch('#search-input', 'searchTerm'); // Watch attribute dataBinder.watch('#user-avatar', 'avatarUrl', { attribute: 'src' }); ``` #### `dataBinder.bindForm(formSelector, dataKey)` Binds form data to the data store. Automatically collects all form fields. ```javascript dataBinder.bindForm('#user-form', 'formData'); ``` #### `dataBinder.bindTable(key, tableSelector, rowTemplate)` Binds array data to a table. Automatically renders rows using the provided template. ```javascript dataBinder.bindTable('users', '#users-table', (user) => ` <td>${user.name}</td> <td>${user.email}</td> <td>${user.role}</td> `); ``` ### API Integration #### `dataBinder.apiCall(url, options)` Makes API calls with automatic data binding. ```javascript // Simple GET request const response = await dataBinder.apiCall('/api/users'); // POST request with data binding await dataBinder.apiCall('/api/users', { method: 'POST', body: JSON.stringify(userData), bindTo: 'users' }); ``` ### Utility Methods #### `dataBinder.cleanup()` Cleans up all watchers and subscribers. Useful for logout or page cleanup. ```javascript // On logout dataBinder.cleanup(); ``` ## Usage Examples ### Simple Data Binding ```javascript // Set up binding dataBinder.bind('message', '#message-display'); // Update data dataBinder.set('message', 'Hello, World!'); // The #message-display element will automatically update ``` ### Form Handling ```javascript // Bind form data dataBinder.bindForm('#user-form', 'userData'); // Subscribe to form changes dataBinder.subscribe('userData', (data) => { console.log('Form data changed:', data); }); // Access form data const formData = dataBinder.get('userData'); ``` ### Table Rendering ```javascript // Set up table binding dataBinder.bindTable('products', '#products-table', (product) => ` <td>${product.name}</td> <td>$${product.price}</td> <td>${product.stock}</td> <td> <button onclick="editProduct(${product.id})">Edit</button> <button onclick="deleteProduct(${product.id})">Delete</button> </td> `); // Load data const products = [ { id: 1, name: 'Product A', price: 29.99, stock: 10 }, { id: 2, name: 'Product B', price: 19.99, stock: 5 } ]; dataBinder.set('products', products); ``` ### API Integration ```javascript // Load user data async function loadUser() { try { await dataBinder.apiCall('/api/user', { bindTo: 'currentUser' }); } catch (error) { console.error('Failed to load user:', error); } } // Save user data async function saveUser(userData) { try { await dataBinder.apiCall('/api/user', { method: 'PUT', body: JSON.stringify(userData), bindTo: 'currentUser' }); } catch (error) { console.error('Failed to save user:', error); } } ``` ### Reactive Counter ```javascript // Set up counter dataBinder.bind('counter', '#counter-display'); dataBinder.set('counter', 0); // Counter functions function increment() { const current = dataBinder.get('counter'); dataBinder.set('counter', current + 1); } function decrement() { const current = dataBinder.get('counter'); dataBinder.set('counter', current - 1); } ``` ## Best Practices ### 1. Initialize Bindings Early Set up all data bindings in the `DOMContentLoaded` event or at the top of your script. ```javascript document.addEventListener('DOMContentLoaded', function() { // Set up all bindings here dataBinder.bind('user', '#user-name'); dataBinder.bindForm('#user-form', 'formData'); dataBinder.bindTable('users', '#users-table', userTemplate); }); ``` ### 2. Use Descriptive Keys Use clear, descriptive keys for your data to make debugging easier. ```javascript // Good dataBinder.set('currentUser', userData); dataBinder.set('productList', products); // Avoid dataBinder.set('u', userData); dataBinder.set('p', products); ``` ### 3. Handle Errors Gracefully Always handle errors in API calls and data operations. ```javascript async function loadData() { try { await dataBinder.apiCall('/api/data', { bindTo: 'myData' }); } catch (error) { console.error('Failed to load data:', error); dataBinder.set('myData', []); } } ``` ### 4. Clean Up on Page Unload Clean up bindings when the page is unloaded to prevent memory leaks. ```javascript window.addEventListener('beforeunload', function() { dataBinder.cleanup(); }); ``` ### 5. Use Subscriptions for Side Effects Use subscriptions to handle side effects like logging, analytics, or complex UI updates. ```javascript dataBinder.subscribe('user', (user) => { // Update multiple UI elements updateUserProfile(user); updateUserMenu(user); trackUserActivity(user); }); ``` ## Migration from appState If you're migrating from the old `appState` system, here's how to convert your code: ### Old Way (appState) ```javascript // Store data appState.user = userData; appState.events = events; // Access data const user = appState.user; const events = appState.events; // Manual DOM updates document.getElementById('user-name').textContent = user.name; ``` ### New Way (Data Binding) ```javascript // Store data dataBinder.set('user', userData); dataBinder.set('events', events); // Access data const user = dataBinder.get('user'); const events = dataBinder.get('events'); // Automatic DOM updates dataBinder.bind('user', '#user-name'); dataBinder.bindTable('events', '#events-table', eventTemplate); ``` ## Browser Compatibility The Data Binding System works in all modern browsers that support: - ES6 Classes - Arrow Functions - Template Literals - Async/Await - Fetch API - MutationObserver This includes: - Chrome 60+ - Firefox 55+ - Safari 12+ - Edge 79+ ## Performance Considerations - The system uses efficient event delegation and minimal DOM manipulation - Subscribers are called only when data actually changes - Watchers use MutationObserver for efficient DOM change detection - Memory is automatically cleaned up when using the `cleanup()` method ## Debugging Enable console logging to debug data binding issues: ```javascript // Subscribe to all data changes for debugging dataBinder.subscribe('*', (key, value) => { console.log(`Data changed: ${key} =`, value); }); ``` ## Example Page Visit `/data-binding-example` to see live examples of all the data binding features in action.
0
đ Page Notes
+ Add New
Add New Note
Type
âšī¸ Info
đ Bug
⨠Feature Request
đĄ Improvement
â Missing Feature
đ¨ Design Changes
Title (optional)
Note Content
đ Add Note