JavaScript API

Complete reference for DBindly methods and events

DBindly exposes a comprehensive JavaScript API for programmatic control over data loading, rendering, and form handling.

Initialization

init(config)

Initialize DBindly with configuration options.

DBindly.init({
  apiUrl: 'https://api.dbindly.com',
  apiKey: 'pk_live_your_api_key',
  cache: true,
  cacheTTL: 300000,
  debug: false,
  retryAttempts: 3,
  retryDelay: 1000,
  timeout: 10000,
  showSkeletons: true,
  onLoad: (data) => console.log('Loaded:', data),
  onError: (error) => console.error('Error:', error),
  onDataLoaded: (data) => console.log('Rendered:', data)
});

Returns: DBindly instance for chaining.

reset()

Reset DBindly to initial state. Clears loaded data and cache.

DBindly.reset();

Returns: DBindly instance for chaining.

isReady()

Check if DBindly has been initialized.

if (DBindly.isReady()) {
  // Safe to use other methods
}

Returns: boolean

Data Loading

load(dataId)

Load data by ID and render it to the DOM.

const data = await DBindly.load('product-123');
console.log(data);

Parameters:

  • dataId (string) - Unique identifier for the data

Returns: Promise<Record<string, unknown>> - The loaded data

fetchData(dataId)

Fetch data by ID without rendering. Useful when you need the data but don't want automatic DOM updates.

const data = await DBindly.fetchData('user-profile');
// Process data manually
processUserData(data);

Parameters:

  • dataId (string) - Unique identifier for the data

Returns: Promise<Record<string, unknown>> - The fetched data

fetchBatch(dataIds, fields?)

Fetch multiple data items in a single request.

const data = await DBindly.fetchBatch(
  ['product-1', 'product-2', 'product-3'],
  ['name', 'price', 'image'] // Optional: specific fields only
);

Parameters:

  • dataIds (string[]) - Array of data identifiers
  • fields (string[], optional) - Specific fields to return

Returns: Promise<Record<string, unknown>> - Merged data object

fetchCollection(slug, options?)

Fetch collection data with pagination, sorting, and filtering.

const result = await DBindly.fetchCollection('products', {
  page: 1,
  limit: 20,
  sort: { field: 'price', direction: 'asc' },
  filters: [
    { field: 'category', operator: 'eq', value: 'electronics' }
  ],
  search: 'laptop'
});
 
console.log(result.data);       // Array of items
console.log(result.total);      // Total count
console.log(result.page);       // Current page
console.log(result.totalPages); // Total pages
console.log(result.hasMore);    // More pages available

Parameters:

  • slug (string) - Collection slug/identifier
  • options (object, optional):
    • page (number) - Page number (1-indexed)
    • limit (number) - Items per page
    • sort (object) - { field: string, direction: 'asc' | 'desc' }
    • filters (array) - Filter configurations
    • search (string) - Search query

Returns: Promise<CollectionResponse>

Rendering

render(data)

Render data to the DOM using data attributes.

DBindly.render({
  title: 'Hello World',
  description: 'Welcome to DBindly',
  image: 'https://example.com/hero.jpg'
});

Parameters:

  • data (object) - Data object to render

renderCollection(slug, options?)

Fetch and render a collection with automatic pagination controls.

await DBindly.renderCollection('blog-posts', {
  limit: 10,
  sort: { field: 'createdAt', direction: 'desc' }
});

Parameters: Same as fetchCollection()

Returns: Promise<CollectionResponse>

Form Data (v2.3.0)

getFormData()

Get all values from elements with dbind_model attribute.

const formData = DBindly.getFormData();
// {
//   username: 'john_doe',
//   email: 'john@example.com',
//   newsletter: true,
//   'user.profile.bio': 'Hello!'
// }

Returns: Record<string, unknown> - Object with field paths as keys

setData(updates)

Update local data and re-render affected elements.

DBindly.setData({
  username: 'jane_doe',
  email: 'jane@example.com'
});

Parameters:

  • updates (object) - Partial data updates to merge

Error Handling (v2.3.0)

showError(message, field?)

Display an error message.

// General error
DBindly.showError('Something went wrong. Please try again.');
 
// Field-specific error
DBindly.showError('Invalid email address', 'email');
DBindly.showError('Password is required', 'user.password');

Parameters:

  • message (string) - Error message to display
  • field (string, optional) - Field name for field-specific errors

clearErrors()

Clear all error messages.

DBindly.clearErrors();

Cache & Metrics

clearCache()

Clear the localStorage cache.

DBindly.clearCache();

Returns: DBindly instance for chaining

getMetrics()

Get performance metrics.

const metrics = DBindly.getMetrics();
console.log(metrics);
// {
//   requestCount: 15,
//   totalLoadTime: 2340,
//   cacheHits: 8,
//   cacheMisses: 7,
//   errors: 0,
//   averageLoadTime: 156,  // Calculated
//   cacheHitRate: 0.53     // Calculated
// }

Returns: DBindlyMetrics object

getData(dataId?)

Get loaded data.

// Get all loaded data
const allData = DBindly.getData();
 
// Get specific data by ID
const product = DBindly.getData('product-123');

Parameters:

  • dataId (string, optional) - Specific data ID to retrieve

Returns: Record<string, unknown>

Properties

version

Current DBindly version string.

console.log(DBindly.version); // "2.3.0"

Events

DBindly dispatches custom events on the document object.

dbindly:model-change

Fired when a dbind_model input value changes.

document.addEventListener('dbindly:model-change', (e) => {
  console.log('Field:', e.detail.field);
  console.log('Value:', e.detail.value);
  console.log('Element:', e.detail.element);
});

Event detail:

  • field (string) - Field path that changed
  • value (unknown) - New value
  • element (HTMLElement) - Input element

dbindly:action

Fired when a dbind_click or dbind_submit action is triggered.

document.addEventListener('dbindly:action', (e) => {
  console.log('Action:', e.detail.action);
  console.log('Data:', e.detail.data);
  console.log('Element:', e.detail.element);
 
  if (e.detail.action === 'save-form') {
    saveData(e.detail.data);
  }
});

Event detail:

  • action (string) - Action name
  • data (object) - Associated data (form values for submit)
  • element (HTMLElement) - Triggering element

dbindly:error

Fired when an error occurs.

document.addEventListener('dbindly:error', (e) => {
  console.log('Error:', e.detail.error);
  console.log('Field:', e.detail.field);
 
  // Send to error tracking
  trackError(e.detail.error);
});

Event detail:

  • error (Error) - Error object
  • field (string, optional) - Associated field name

dbindly:loaded

Fired when data is successfully loaded.

document.addEventListener('dbindly:loaded', (e) => {
  console.log('Data loaded:', e.detail.data);
});

Event detail:

  • data (object) - Loaded data

dbindly:collection-loaded

Fired when a collection is loaded.

document.addEventListener('dbindly:collection-loaded', (e) => {
  console.log('Collection:', e.detail.slug);
  console.log('Data:', e.detail.data);
});

Event detail:

  • slug (string) - Collection slug
  • data (CollectionResponse) - Collection response

Complete Example

// Initialize
DBindly.init({
  apiUrl: 'https://api.example.com',
  apiKey: 'pk_live_xxx',
  debug: true,
  onError: (error) => {
    DBindly.showError(error.message);
  }
});
 
// Listen for form changes
document.addEventListener('dbindly:model-change', (e) => {
  console.log(`${e.detail.field} changed to ${e.detail.value}`);
});
 
// Handle form submission
document.addEventListener('dbindly:action', async (e) => {
  if (e.detail.action === 'submit-form') {
    DBindly.clearErrors();
 
    try {
      const response = await fetch('/api/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(e.detail.data)
      });
 
      if (!response.ok) {
        const error = await response.json();
        DBindly.showError(error.message, error.field);
        return;
      }
 
      // Success - reload data
      await DBindly.load('user-profile');
    } catch (err) {
      DBindly.showError('Network error. Please try again.');
    }
  }
});
 
// Load initial data
await DBindly.load('user-profile');
 
// Check metrics
const metrics = DBindly.getMetrics();
console.log(`Cache hit rate: ${(metrics.cacheHitRate * 100).toFixed(1)}%`);

Next Steps