Overview
Event subscribers in EverShop:- React to system events without modifying core code
- Execute asynchronously to avoid blocking main operations
- Can be chained - multiple subscribers can listen to the same event
- Are easy to test and maintain
- Support both sync and async operations
How Events Work
When an action occurs in EverShop (e.g., a product is created), the system emits an event. Subscribers listening to that event are automatically executed.Directory Structure
Event subscribers are organized by event name:Creating Your First Subscriber
Real-World Example
Here’s the actual subscriber from the sample extension:extensions/sample/src/subscribers/product_created/consoleLog.js
Common Events
Here are common events you can subscribe to:Product Events
Order Events
Customer Events
Advanced Examples
Send Email on Order
src/subscribers/order_placed/sendConfirmationEmail.js
Update Inventory
src/subscribers/order_placed/updateInventory.js
Log to Database
src/subscribers/product_updated/logChange.ts
Webhook Integration
src/subscribers/order_placed/notifyWarehouse.js
Customer Segmentation
src/subscribers/customer_registered/addToSegment.js
Multiple Subscribers per Event
You can have multiple subscribers for the same event:Async/Await Support
Subscribers fully support async operations:Error Handling
Always implement proper error handling:Data Access Patterns
Destructure Event Data
Validate Data
Testing Subscribers
Manual Testing
Trigger events manually in development:Unit Testing
Best Practices
- Error Handling - Always wrap logic in try-catch blocks
- Logging - Log both successes and failures for debugging
- Async Operations - Use async/await for cleaner code
- Validation - Validate event data before processing
- Idempotency - Design subscribers to handle duplicate events
- Performance - Avoid blocking operations; use queues for heavy tasks
- Testing - Write unit tests for business logic
Common Use Cases
Email Notifications
External Integrations
Internal Operations
Troubleshooting
Subscriber Not Executing
- Verify directory name matches event name exactly
- Check subscriber exports a default function
- Run
npm run buildto rebuild - Check extension is enabled in
config/default.json - Verify the event is actually being emitted
Errors in Subscriber
- Add try-catch blocks to identify errors
- Check console logs for error messages
- Verify event data structure matches expectations
- Test subscriber in isolation
Performance Issues
- Move heavy operations to background jobs
- Implement queuing for external API calls
- Use caching where appropriate
- Profile subscriber execution time
Next Steps
Cron Jobs
Schedule background tasks
API Endpoints
Create custom API endpoints