Callbacks
Ejecuta código personalizado cuando ocurren eventos en el widget.
Única forma de responder a eventos
Los callbacks son la única forma de responder a eventos del widget. Se configuran en NeuroonWidget.init() y no existe un método widget.on() para suscribirse a eventos después de la inicialización.
Callbacks disponibles
NeuroonWidget.init({
// ...
callbacks: {
onSearch: (query: string) => void,
onResultClick: (product: Product) => void,
onFilterChange: (filters: AppliedFilters) => void,
onError: (error: Error) => void,
},
});
onSearch
Se ejecuta después de cada búsqueda (texto, voz o imagen).
onSearch: (query) => {
console.log('Búsqueda realizada:', query);
// Google Analytics
gtag('event', 'search', {
search_term: query,
});
// Facebook Pixel
fbq('track', 'Search', {
search_string: query,
});
}
Parámetros:
query(string): Texto de la búsqueda realizada
onResultClick
Se ejecuta cuando el usuario hace clic en un producto.
onResultClick: (product) => {
console.log('Producto:', product.name);
// Facebook Pixel
fbq('track', 'ViewContent', {
content_ids: [product.id],
content_name: product.name,
value: product.price,
currency: 'EUR',
});
// Google Analytics
gtag('event', 'select_item', {
items: [{
item_id: product.id,
item_name: product.name,
price: product.price,
}],
});
}
Parámetros:
product(Product): Objeto del producto clickeado
interface Product {
id: string;
name: string;
description?: string;
price: number;
salePrice?: number;
currency: string;
url: string;
imageUrl?: string;
categories: string[];
brands: string[];
tags: string[];
inStock: boolean;
score?: number;
}
onFilterChange
Se ejecuta cuando cambian los filtros aplicados.
onFilterChange: (filters) => {
console.log('Filtros aplicados:', filters);
// Analytics
gtag('event', 'filter_applied', {
categories: filters.categories?.join(','),
brands: filters.brands?.join(','),
price_range: `${filters.priceMin}-${filters.priceMax}`,
});
}
Parámetros:
filters(AppliedFilters): Filtros activos
interface AppliedFilters {
priceMin?: number;
priceMax?: number;
categories?: string[];
brands?: string[];
tags?: string[];
inStock?: boolean;
onSale?: boolean;
sortBy?: 'relevance' | 'price_asc' | 'price_desc' | 'rating' | 'newest' | 'popularity' | 'discount';
}
onError
Se ejecuta cuando ocurre un error en el widget (búsqueda fallida, token inválido, etc.).
onError: (error) => {
console.error('Error en widget:', error.message);
// Enviar a servicio de monitoreo
Sentry.captureException(error);
// O analytics
gtag('event', 'exception', {
description: error.message,
fatal: false,
});
}
Parámetros:
error(Error): Objeto de error conmessageystack
Ejemplo completo
const widget = NeuroonWidget.init({
container: '#neuroon-search',
token: 'YOUR_TOKEN',
callbacks: {
onSearch: (query) => {
gtag('event', 'search', { search_term: query });
},
onResultClick: (product) => {
// Facebook Pixel
fbq('track', 'ViewContent', {
content_ids: [product.id],
content_type: 'product',
value: product.price,
currency: product.currency,
});
// Google Analytics
gtag('event', 'select_item', {
items: [{
item_id: product.id,
item_name: product.name,
price: product.price,
}],
});
},
onFilterChange: (filters) => {
gtag('event', 'filter_applied', {
categories: filters.categories?.join(','),
brands: filters.brands?.join(','),
price_range: `${filters.priceMin}-${filters.priceMax}`,
});
},
onError: (error) => {
console.error('Widget error:', error.message);
},
},
});
Orden de ejecución
Los callbacks se ejecutan en el siguiente orden:
onSearch- Después de ejecutar una búsquedaonFilterChange- Cuando cambian los filtrosonResultClick- Al hacer clic en un productoonError- Cuando ocurre un error (puede ocurrir en cualquier momento)
Próximamente
Los siguientes callbacks están planificados para futuras versiones:
| Callback | Descripción |
|---|---|
onConversion | Trackear conversiones (añadir al carrito, compra) |
onTokenExpiring | Renovar token antes de que expire |