or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

app-component.mdbiometric-auth.mdbluetooth.mddevice-system.mdevents.mdindex.mdlocation-maps.mdmedia-camera.mdnative-integration.mdnavigation.mdnetwork.mdstorage-filesystem.mdui.mdutilities.md
tile.json

events.mddocs/

Event System APIs

Custom event handling and communication system for inter-component communication.

Capabilities

Event Registration

Register event listeners for custom events across the application.

/**
 * Listen to custom event
 * @param eventName - Name of the event to listen for
 * @param callback - Callback function to execute when event is triggered
 */
function $on(eventName: string, callback: Function): void;

/**
 * Listen to custom event once (auto-removes after first trigger)
 * @param eventName - Name of the event to listen for
 * @param callback - Callback function to execute when event is triggered
 */
function $once(eventName: string, callback: Function): void;

Usage Examples:

import uni from "@dcloudio/uni-app-plus";

// Listen for user login event
uni.$on('userLogin', (userInfo) => {
  console.log('User logged in:', userInfo);
  // Update UI state
  this.isLoggedIn = true;
  this.currentUser = userInfo;
});

// Listen for data refresh event
uni.$on('dataRefresh', (data) => {
  console.log('Data refreshed:', data);
  this.refreshLocalData(data);
});

// Listen for theme change event (once only)
uni.$once('themeChanged', (theme) => {
  console.log('Theme changed to:', theme);
  this.applyTheme(theme);
  // This listener will be automatically removed after first trigger
});

// Listen for error events with detailed handler
uni.$on('appError', (error) => {
  console.error('Application error:', error);
  
  // Handle different error types
  switch (error.type) {
    case 'network':
      this.handleNetworkError(error);
      break;
    case 'validation':
      this.showValidationError(error.message);
      break;
    default:
      this.showGenericError(error);
  }
});

Event Emission

Emit custom events to notify other parts of the application.

/**
 * Emit custom event
 * @param eventName - Name of the event to emit
 * @param args - Arguments to pass to event listeners
 */
function $emit(eventName: string, ...args: any[]): void;

Usage Examples:

// Emit user login event
uni.$emit('userLogin', {
  id: 12345,
  name: 'John Doe',
  email: 'john@example.com',
  role: 'user'
});

// Emit data update event with multiple parameters
uni.$emit('dataUpdate', 'users', newUserData, { timestamp: Date.now() });

// Emit navigation event
uni.$emit('navigate', {
  page: '/pages/profile/profile',
  params: { userId: 123 }
});

// Emit error event
uni.$emit('appError', {
  type: 'network',
  message: 'Failed to connect to server',
  code: 'NETWORK_ERROR',
  details: error
});

// Emit status change
uni.$emit('statusChange', {
  from: 'loading',
  to: 'ready',
  data: responseData
});

// Emit simple notification
uni.$emit('notification', 'Data saved successfully');

Event Removal

Remove event listeners when they are no longer needed.

/**
 * Remove event listener(s)
 * @param eventName - Name of the event (optional)
 * @param callback - Specific callback to remove (optional)
 */
function $off(eventName?: string, callback?: Function): void;

Usage Examples:

// Remove specific event listener
const loginHandler = (userInfo) => {
  console.log('Login handler:', userInfo);
};

uni.$on('userLogin', loginHandler);
// Later remove the specific listener
uni.$off('userLogin', loginHandler);

// Remove all listeners for an event
uni.$off('dataRefresh');

// Remove all event listeners (use with caution)
uni.$off();

// Pattern: Register and cleanup in component lifecycle
export default {
  data() {
    return {
      userData: null
    };
  },
  
  onLoad() {
    // Register event listeners
    this.userLoginHandler = (userInfo) => {
      this.userData = userInfo;
    };
    
    this.dataUpdateHandler = (type, data) => {
      if (type === 'user') {
        this.userData = data;
      }
    };
    
    uni.$on('userLogin', this.userLoginHandler);
    uni.$on('dataUpdate', this.dataUpdateHandler);
  },
  
  onUnload() {
    // Clean up event listeners
    uni.$off('userLogin', this.userLoginHandler);
    uni.$off('dataUpdate', this.dataUpdateHandler);
  }
};

Common Event Patterns

Application State Events

Standard event patterns for application state management.

// Common application events
interface AppEvents {
  'app:ready': () => void;
  'app:error': (error: AppError) => void;
  'user:login': (user: UserInfo) => void;
  'user:logout': () => void;
  'data:update': (type: string, data: any) => void;
  'navigation:change': (route: RouteInfo) => void;
  'theme:change': (theme: ThemeInfo) => void;
}

Usage Example:

// App initialization
uni.$on('app:ready', () => {
  console.log('Application ready');
  initializeApp();
});

// User management
uni.$on('user:login', (user) => {
  console.log('User logged in:', user.name);
  updateUserInterface(user);
  loadUserPreferences(user.id);
});

uni.$on('user:logout', () => {
  console.log('User logged out');
  clearUserInterface();
  redirectToLogin();
});

// Data synchronization
uni.$on('data:update', (type, data) => {
  console.log(`Data updated - ${type}:`, data);
  
  switch (type) {
    case 'profile':
      updateProfileView(data);
      break;
    case 'settings':
      updateSettingsView(data);
      break;
    case 'notifications':
      updateNotificationBadge(data.count);
      break;
  }
});

// Theme management
uni.$on('theme:change', (theme) => {
  console.log('Theme changed:', theme.name);
  applyThemeStyles(theme);
  saveThemePreference(theme.id);
});

Component Communication

Event patterns for component-to-component communication.

// Parent-child communication
export default {
  methods: {
    // Parent component
    handleChildEvent() {
      uni.$on('child:action', (data) => {
        console.log('Child performed action:', data);
        this.handleChildAction(data);
      });
    },
    
    // Notify child components
    notifyChildren(message) {
      uni.$emit('parent:message', message);
    }
  }
};

// Child component
export default {
  methods: {
    // Listen for parent messages
    onLoad() {
      uni.$on('parent:message', (message) => {
        console.log('Message from parent:', message);
        this.handleParentMessage(message);
      });
    },
    
    // Notify parent
    notifyParent(data) {
      uni.$emit('child:action', data);
    }
  }
};

// Sibling component communication
export default {
  methods: {
    // Component A
    sendToSibling(data) {
      uni.$emit('sibling:data', data);
    },
    
    // Component B
    onLoad() {
      uni.$on('sibling:data', (data) => {
        console.log('Data from sibling:', data);
        this.processSiblingData(data);
      });
    }
  }
};

Error Handling Events

Centralized error handling through events.

// Error event registration
uni.$on('error:network', (error) => {
  console.error('Network error:', error);
  
  uni.showToast({
    title: 'Network error occurred',
    icon: 'none',
    duration: 3000
  });
});

uni.$on('error:validation', (error) => {
  console.error('Validation error:', error);
  
  uni.showModal({
    title: 'Validation Error',
    content: error.message,
    showCancel: false
  });
});

uni.$on('error:auth', (error) => {
  console.error('Authentication error:', error);
  
  uni.showModal({
    title: 'Authentication Required',
    content: 'Please log in to continue',
    success: (res) => {
      if (res.confirm) {
        uni.navigateTo({
          url: '/pages/login/login'
        });
      }
    }
  });
});

// Emit errors from anywhere in the app
const handleApiError = (error) => {
  if (error.code === 'NETWORK_ERROR') {
    uni.$emit('error:network', error);
  } else if (error.code === 'VALIDATION_ERROR') {
    uni.$emit('error:validation', error);
  } else if (error.code === 'AUTH_ERROR') {
    uni.$emit('error:auth', error);
  }
};

Types

Event System Types

interface EventCallback {
  (...args: any[]): void;
}

interface EventListener {
  callback: EventCallback;
  once: boolean;
}

interface EventMap {
  [eventName: string]: EventListener[];
}

interface AppError {
  type: 'network' | 'validation' | 'auth' | 'system';
  message: string;
  code: string;
  details?: any;
}

interface UserInfo {
  id: number;
  name: string;
  email: string;
  avatar?: string;
  role: string;
}

interface RouteInfo {
  path: string;
  params?: object;
  query?: object;
}

interface ThemeInfo {
  id: string;
  name: string;
  colors: object;
  styles: object;
}