Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Understanding Scene Values, Page Registration, Routing, and Modularization in Mini Programs

Tech 1

Scene Values

Scene values identify the entry point through which a user accessed the Mini Program. This information is useful for tracking traffic sources and tailoring marketing campaigns accordingly.

These values are available within the onLaunch and onShow lifecycle methods of the App() constructor. For certain scenes, additional data like the source AppId (for another app, official account, or Mini Program) can also be retrieved.

Note: Support for scene values began with Base Library 1.1.0. Applications targeting earlier versions require compatibility handling.

The following is a partial list of defined scene values:

  • 1001: Mini Program main entry in Discover
  • 1005: Results page from the top search bar
  • 1006: Results page from the search box within the Discover Mini Program entry
  • 1007: Mini Program message card in a single-user chat
  • 1008: Mini Program message card in a group chat
  • 1011: QR code scan
  • 1012: Long-press to recognize QR code from image
  • 1013: Select QR code from phone album
  • 1014: Mini Program template message
  • 1017: Entry page for the Trial Version
  • 1019: WeChat Pay
  • 1020: Related Mini Programs list on an Official Account profile page
  • 1022: Pinned Mini Program entry at the top of a chat
  • 1023: Android system desktop icon
  • 1024: Mini Program profile page
  • 1025: 1D barcode scan
  • 1026: Nearby Mini Programs list
  • 1027: "Used Mini Programs" list in the top search bar results page
  • 1028: My Cards
  • 1029: Card detail page
  • 1030: Open via automated testing
  • 1031: Long-press to recognize 1D barcode from image
  • 1032: Select 1D barcode from phone album
  • 1034: WeChat Pay completion page
  • 1035: Official Account custom menu
  • 1036: App share message card
  • 1037: Open a Mini Program from another Mini Program
  • 1038: Return from another Mini Program
  • 1039: Shake for TV
  • 1042: Results page from the "Add Friend" search box
  • 1043: Official Account template message
  • 1044: Mini Program message card with shareTicket
  • 1047: Mini Program code scan
  • 1048: Long-press to recognize Mini Program code from image
  • 1049: Select Mini Program code from phone album
  • 1052: Applicable store list for a coupon
  • 1053: Search results page
  • 1054: Mini Program quick entry in the top search bar
  • 1056: Music player menu
  • 1057: Bank card detail page in WeChat Pay
  • 1058: Official Account article
  • 1059: Trial version binding invitation page
  • 1064: WeChat Wi-Fi status bar
  • 1067: Advertisement in an Official Account article
  • 1068: Advertisement in the Nearby Mini Programs list
  • 1071: Bank card list page in WeChat Pay
  • 1072: QR code payment collection page
  • 1073: Mini Program message card sent in customer service message list
  • 1074: Mini Program message card sent in Official Account conversation
  • 1078: Wi-Fi connection success page
  • 1089: Pull down from the main WeChat chat interface
  • 1090: Long-press the Mini Program menu in the top-right to show recent usage history
  • 1092: City Services entry

Android Limitation: Due to Android system restrictions, the scene value cannot be captured when a user exits to the home screen via the Home button and then re-enters the Mini Program. In such cases, the previous scene value is retained.

Page Registration

The Page() constructor is used to define a page. It accepts a configuration object specifying initial data, lifecycle callbacks, and event handlers.

The object undergoes a deep copy during page initialization; consider the data size's impact on load performance.

Example registration:

// homePage.js
Page({
  pageData: {
    greeting: "Initial page data."
  },
  onLoad: function(entryParams) {
    // Initialization logic when page loads.
  },
  onReady: function() {
    // Logic executed when page render is complete.
  },
  onShow: function() {
    // Logic executed each time the page becomes visible.
  },
  onHide: function() {
    // Logic executed when the page is hidden.
  },
  onUnload: function() {
    // Cleanup logic when the page is unloaded.
  },
  onPullDownRefresh: function() {
    // Handler for user pull-to-refresh action.
  },
  onReachBottom: function() {
    // Handler triggered when user scrolls to page bottom.
  },
  onShareAppMessage: function () {
   // Returns custom data for sharing.
   return {
     title: 'Shared Content',
     path: '/pages/index?id=123'
   }
  },
  onPageScroll: function(scrollInfo) {
    // Handler for page scroll events.
  },
  onTabItemTap(tabInfo) {
    console.log(tabInfo.index, tabInfo.pagePath, tabInfo.text)
  },
  // Custom event handler.
  handleViewTap: function() {
    this.setData({
      greeting: 'Updated view data.'
    }, function() {
      // Callback executed after setData completes.
    })
  },
  // Custom data section.
  internalData: {
    name: 'Framework'
  }
})

Initialization Data

The data field provides the initial state for the page's first render. This data is serialized to JSON and passed to the view layer, where it can be bound using WXML.

WXML:

<view>{{greeting}}</view>
<view>{{list[1].content}}</view>

JavaScript:

Page({
  data: {
    greeting: 'Status:',
    list: [{content: 'Item A'}, {content: 'Item B'}]
  }
})

Lifecycle Callbacks

  • onLoad: Invoked once when the page loads. Query parameters from the opening path are accessible here.
  • onShow: Invoked each time the page becomes visible.
  • onReady: Invoked once when the initial page render is complete. UI configuration (e.g., wx.setNavigationBarTitle) should be done after this callback.
  • onHide: Invoked when the page is hidden (e.g., by navigateTo or switching bottom tabs).
  • onUnload: Invoked when the page is unloaded (e.g., by redirectTo or navigateBack).

Page Event Handlers

  • onPullDownRefresh: Listens for the pull-to-refresh gesture. Requires enabling enablePullDownRefresh in app.json or the page configuration. Call wx.stopPullDownRefresh() to conclude the refresh.
  • onReachBottom: Listens for when the user scrolls to the bottom. The trigger distance is configurable via onReachBottomDistance in app.json or page config.
  • onPageScroll(Object scrollInfo): Listens for page scroll events.
  • onShareAppMessage(): Defines custom content for sharing. The share menu button only appears if this function is defined. It must return an object with fields like title and path.

Custom Event Handlers

Functions defined in the Page object can be bound to component events in WXML.

WXML:

<view bindtap="handleTapEvent">Tap Here</view>

JavaScript:

Page({
  handleTapEvent: function() {
    console.log('Event triggered')
  }
})

The setData Method

The Page.prototype.setData(Object data, Function callback) method is used to send data asynchronously from the logic layer to the view layer, while synchronously updating the corresponding value in this.data.

Key points:

  1. Direct modification of this.data does not update the view and causes data inconsistency. Always use setData.
  2. The data size for a single setData call must not exceed 1024KB.
  3. Avoid setting any value in data to undefined.

The key in the data object can be a path, such as 'list[0].text' or 'user.profile.name', and does not need to be pre-defined in this.data.

Example: WXML:

<view>{{message}}</view>
<button bindtap="modifyMessage">Update Message</button>
<view>{{nested.item.value}}</view>
<button bindtap="modifyNested">Update Nested Data</button>

JavaScript:

Page({
  data: {
    message: 'Initial',
    nested: { item: { value: 'Start' } }
  },
  modifyMessage: function() {
    this.setData({
      message: 'Updated'
    })
  },
  modifyNested: function() {
    this.setData({
      'nested.item.value': 'Changed'
    })
  }
})

Page Routing

The framework manages all page routing. It maintains a page stack representing the current navigation state.

The Page Stack

The getCurrentPages() function returns an array representing the current page stack, with the first element being the homepage and the last element being the active page.

Warning: Do not modify the returned page stack array, as it will cause routing errors.

Routing Methods and Lifecycles

Different routing methods trigger specific page lifecycle sequences:

  • navigateTo: Opens a non-tabBar page. The current page's onHide is called, and the new page's onLoad, onShow, onReady are called.
  • redirectTo: Closes the current page and opens a non-tabBar page. The current page's onUnload is callled, and the new page's lifecycle callbacks follow.
  • switchTab: Switches to a tabBar page. All non-tabBar pages are destroyed.
  • navigateBack: Closes the current page and returns to a previous one. The closed page's onUnload is called, and the reopened page's onShow is called.
  • reLaunch: Closes all pages and opens a new one (can be any page).

Rules:

  • navigateTo and redirectTo can only open non-tabBar pages.
  • switchTab can only open tabBar pages.
  • reLaunch can open any page.
  • Parameters passed during routing are available in the target page's onLoad method.

Modularization

File Scope

Variables and functions declared in a JavaScript file have scope limited to that file. Identically named entities in different files do not conflict.

The global application instance can be retrieved via getApp(). Global data can be set in the App() constructor.

Example: app.js:

App({
  appGlobalState: 10
})

moduleA.js:

var localA = 'Value A'
var appInstance = getApp()
appInstance.appGlobalState += 5 // Modifies global data.

moduleB.js:

var localA = 'Value B' // Independent of moduleA.js
console.log(getApp().appGlobalState) // Logs 15 if moduleA ran first.

Module Exports

Common code can be extracted into a module file. Interfaces are exposed using module.exports or exports.

Note: exports is a reference to module.exports. Reassigning exports can cause errors. Using module.exports is generally safer. Node module are not directly supported. Relevant code must be copied into the project directory.

utilities.js:

function logWelcome(user) {
  console.log(`Welcome, ${user}!`)
}
function logFarewell(user) {
  console.log(`Goodbye, ${user}!`)
}

module.exports = {
  welcomeUser: logWelcome,
  farewellUser: logFarewell
}

Importing the module:

var utils = require('utilities.js')
Page({
  onLoad: function() {
    utils.welcomeUser('Developer')
    utils.farewellUser('Developer')
  }
})

API Overview

The framework provides a rich set of native WeChat APIs for features like user info, local storage, and payment.

Conventions:

  • APIs prefixed with wx.on are listeners that accept a callback function to be executed when the event occurs.
  • Other APIs generally accept an OBJECT parameter.
  • This parameter object can include success, fail, and complete callbacks to handle the operation's result.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.