or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

api-interceptors.mdconfig-compilation.mdevent-system.mdframework-runtime.mdindex.mdmp-runtime.mdutility-functions.mdwxs-utilities.md
tile.json

event-system.mddocs/

Event System

Vue.js-compatible event system that integrates with WeChat Mini Program's event handling model. Provides global event communication between components, pages, and the application using Vue's event emitter pattern.

Capabilities

Event Subscription

Subscribe to custom events using Vue.js event handling patterns.

/**
 * Subscribe to custom events
 * @param event - Event name to listen for
 * @param callback - Function to call when event is emitted
 * @returns Result from Vue.$on method
 */
function $on(event: string, callback: Function): any;

Usage Example:

import uni from "@dcloudio/uni-mp-weixin";

// Listen for user login events
uni.$on('userLogin', (userInfo) => {
  console.log('User logged in:', userInfo);
  // Update UI or perform actions
});

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

// Listen for multiple events
uni.$on('networkStatus', (status) => {
  if (status.isConnected) {
    console.log('Network connected');
  } else {
    console.log('Network disconnected');
  }
});

Event Unsubscription

Remove event listeners to prevent memory leaks and unwanted event handling.

/**
 * Unsubscribe from custom events
 * @param event - Event name to stop listening for (optional)
 * @param callback - Specific callback to remove (optional)
 * @returns Result from Vue.$off method
 */
function $off(event?: string, callback?: Function): any;

Usage Example:

import uni from "@dcloudio/uni-mp-weixin";

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

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

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

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

One-time Event Subscription

Subscribe to events that should only fire once, automatically removing the listener after the first emission.

/**
 * Subscribe to custom event that fires only once
 * @param event - Event name to listen for once
 * @param callback - Function to call when event is emitted
 * @returns Result from Vue.$once method
 */
function $once(event: string, callback: Function): any;

Usage Example:

import uni from "@dcloudio/uni-mp-weixin";

// Listen for app initialization (only once)
uni.$once('appInitialized', (config) => {
  console.log('App initialized with config:', config);
  // Perform one-time setup
});

// Listen for first-time user registration
uni.$once('userRegistered', (userData) => {
  console.log('New user registered:', userData);
  // Show welcome message or tour
  uni.showModal({
    title: 'Welcome!',
    content: 'Thanks for joining us!',
    showCancel: false
  });
});

Event Emission

Emit custom events to notify subscribers across the application.

/**
 * Emit custom events to all subscribers
 * @param event - Event name to emit
 * @param args - Arguments to pass to event handlers
 * @returns Result from Vue.$emit method
 */
function $emit(event: string, ...args: any[]): any;

Usage Example:

import uni from "@dcloudio/uni-mp-weixin";

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

// Emit data refresh event with multiple arguments
uni.$emit('dataRefresh', newData, { timestamp: Date.now(), source: 'api' });

// Emit network status change
uni.$emit('networkStatus', { 
  isConnected: true, 
  type: 'wifi', 
  strength: 'strong' 
});

// Emit application events
uni.$emit('appInitialized', {
  version: '1.0.0',
  features: ['push', 'location', 'camera']
});

Common Event Patterns

Component Communication

// Child component emitting to parent
// In child component
this.$emit('childEvent', data);

// Parent component listening
uni.$on('globalChildEvent', (data) => {
  // Handle global child events
});

Page Lifecycle Events

// Page emitting lifecycle events
// In page onShow
uni.$emit('pageVisible', { pageName: 'index', timestamp: Date.now() });

// Other components listening
uni.$on('pageVisible', ({ pageName, timestamp }) => {
  console.log(`Page ${pageName} became visible at ${timestamp}`);
});

Data Synchronization

// Data service emitting updates
class DataService {
  updateUserInfo(userInfo) {
    // Update local storage
    uni.setStorageSync('userInfo', userInfo);
    // Notify all subscribers
    uni.$emit('userInfoUpdated', userInfo);
  }
}

// Components listening for updates
uni.$on('userInfoUpdated', (userInfo) => {
  // Update component data
  this.setData({ userInfo });
});

Error Handling Events

// Global error handling
uni.$on('globalError', (error) => {
  console.error('Global error:', error);
  uni.showToast({
    title: 'Something went wrong',
    icon: 'none'
  });
});

// Emit errors from anywhere
try {
  // Some operation
} catch (error) {
  uni.$emit('globalError', error);
}

Best Practices

Memory Management

Always clean up event listeners in component lifecycle hooks:

// In page or component
onLoad() {
  this.handleDataUpdate = (data) => {
    // Handle data update
  };
  uni.$on('dataUpdate', this.handleDataUpdate);
},

onUnload() {
  // Clean up event listeners
  uni.$off('dataUpdate', this.handleDataUpdate);
}

Event Naming

Use consistent naming conventions for events:

// Good: Descriptive and namespaced
uni.$emit('user:login', userInfo);
uni.$emit('data:refresh', data);
uni.$emit('ui:modalClosed', modalId);

// Avoid: Generic or unclear names
uni.$emit('update', data);
uni.$emit('change', value);

Error Handling

Handle potential errors in event callbacks:

uni.$on('someEvent', (data) => {
  try {
    // Process event data
    processData(data);
  } catch (error) {
    console.error('Error handling event:', error);
  }
});