tencent cloud

Feedback

Logic Layer

Last updated: 2024-07-12 17:48:00

    1. Introduce

    At the logic layer of the Mini Program development framework, the JavaScript engine is used to provide a Mini Program with features specific to TCMPP Mini Programs and an environment for running JavaScript code written by developers.
    The logic layer processes data and sends processed data to the view layer, and receives event feedback from the view layer.
    All code written by developers will be packaged into a JavaScript file, which runs when the Mini Program is started until the Mini Program is destroyed. This behavior is similar to ServiceWorker. Therefore, the logic layer is also referred to as an App Service.
    Based on JavaScript, we have added some features to facilitate the development of Mini Programs:
    App and Page methods used for Program Registration and Registering Page;
    getApp and getCurrentPages methods, respectively used to obtain the App instance and the current page stack;
    Rich API, such as Weixin user data, Scan, WeChat Pay, and other Weixin-specific capabilities;
    Modularization capability, allowing each page to have an independent [Scope](./module.md#File Scope).
    Note
    The logic layer of the Mini Program development framework does not run on browsers. Therefore, web-based capabilities of JavaScript, such as window and document, are unavailable.

    2. Registering a Mini Program Account

    For each Mini Program, a Mini Program instance needs to be registered by calling the App method via app.js, to link the lifecycle callback function, error listening function, page not found listening function, and the like.
    For specific definitions and usage of the parameters, refer to App.
    // app.js
    App({
    onLaunch (options) {
    // Do something initial when launch.
    },
    onShow (options) {
    // Do something when show.
    },
    onHide () {
    // Do something when hide.
    },
    onError (msg) {
    console.log(msg)
    },
    globalData: 'I am global data'
    })
    A Mini Program has only one app instance, which is shared to all pages. Developers can obtain the globally unique app instance by using the getApp method, and then obtain data in the app or call a function registered with App by the developers.
    // xxx.js
    const appInstance = getApp()
    console.log(appInstance.globalData) // I am global data

    3. Registering Page

    For each page of a Mini Program, a page instance needs to be registered by calling the Page method via the js file corresponding to the page, to specify the initial data of the page, the lifecycle callback function, the event processing function, and the like of the page.

    3.1 Registering a Page with the Page Constructor

    Simple pages can be constructed using Page().
    Code example:
    // index.js
    Page({
    data: {
    text: "This is page data."
    },
    onLoad: function(options) {
    // Do some initialize when page load.
    },
    onReady: function() {
    // Do something when page ready.
    },
    onShow: function() {
    // Do something when page show.
    },
    onHide: function() {
    // Do something when page hide.
    },
    onUnload: function() {
    // Do something when page close.
    },
    onPullDownRefresh: function() {
    // Do something when pull down.
    },
    onReachBottom: function() {
    // Do something when page reach bottom.
    },
    onShareAppMessage: function () {
    // return custom share data when user share.
    },
    onPageScroll: function() {
    // Do something when page scroll
    },
    onResize: function() {
    // Do something when page resize
    },
    onTabItemTap(item) {
    console.log(item.index)
    console.log(item.pagePath)
    console.log(item.text)
    },
    // Event handler.
    viewTap: function() {
    this.setData({
    text: 'Set some data for updating view.'
    }, function() {
    // this is setData callback
    })
    },
    customData: {
    hi: 'MINA'
    }
    })
    For specific definitions and usage of the parameters, refer to Page.

    3.2 Constructing Pages with the Component Constructor

    The Page constructor works for simple pages. However, for complex pages, the Page constructor may not work well.
    In this case, you can use the Component constructor to construct the page. The main difference of the Component constructor is that the methods need to be inside methods: { }.
    Code example:
    Component({
    data: {
    text: "This is page data."
    },
    methods: {
    onLoad: function(options) {
    // Executed when the page is created
    }, onPullDownRefresh: function() { // Execute on page creation.
    onPullDownRefresh: function() {
    // onPullDownRefresh: function() { // On page creation }, onPullDownRefresh: function()
    }, onPullDownRefresh.
    // Event response function
    viewTap: function() {
    // ...
    }
    }
    })
    This is very similar to a Custom Components in that you can use advanced features such as behaviors in the same way as a custom component.
    Read the Component Constructors section for more details.

    4. Page Lifecycle

    Note
    You don't need to fully understand the following content right away, but it will help in the future.
    The following figure describes the lifecycle of a Page instance.
    

    5. Page Routing

    The framework manages all the routes to pages of a Mini Program.

    5.1 Page Stack

    The framework maintains all the existing pages via stacks. When a route is switched, the page stack reacts as follows:
    Routing
    Reaction on the Page Stack
    Initialization
    The new page is pushed onto the stack.
    Opening a new page
    The new page is pushed onto the stack.
    Page redirection
    The current page is popped out of the stack, and the new page is pushed onto the stack.
    Page return
    Pages are successively popped out of the stack until the destination return page is displayed.
    Tab switching
    All the pages are popped out of the stack, and only the new tab page is retained.
    Reloading
    All the pages are popped out of the stack, and only the new page is retained.
    Developers can use the getCurrentPages() function to get the current page stack, given as an array in the order of the stack, with the first element being the home page and the last element being the current page.
    Note:
    Don't try to modify the page stack, it will cause routing and page state errors.
    Don't call getCurrentPages() on App.onLaunch when the page has not been generated.

    5.2 Routing

    The following shows how page routing is triggered and the lifecycle functions for pages.
    Routing
    Trigger Condition
    Source Page
    Routed-To Page
    Initialization
    A page of the Mini Program is opened for the first time.
    -
    onLoad, onShow
    Opening a new page
    The API wx.navigateTo is called. The component <navigator open-type="navigateTo"/> is used.
    onHide
    onLoad, onShow
    Page redirection
    The API wx.redirectTo is called. The component <navigator open-type="redirectTo"/> is used.
    onUnload
    onLoad, onShow
    Page return
    The API wx.navigateBack is called. The component <navigator open-type="navigateBack"> is used. The user taps the return button on the top left.
    onUnload
    onShow
    Tab switching
    The API wx.switchTab is called. The component <navigator open-type="switchTab"/> is used. The user switches between tabs.
    -
    For details, refer to the following table.
    Restart
    The API wx.reLaunch is called. The component <navigator open-type="reLaunch"/> is used.
    onUnload
    onLoad, onShow
    Lifecycle functions corresponding to tab switching (in the following example, pages A and B are Tabbar pages, page C is obtained after page A is opened, and page D is obtained after page C is opened):
    Current Page
    Routed-To Page
    Triggered Lifecycle Function (In Order)
    A
    A
    Nothing happend
    A
    B
    A.onHide(), B.onLoad(), B.onShow()
    A
    B (Opened again)
    A.onHide(), B.onShow()
    C
    A
    C.onUnload(), A.onShow()
    C
    B
    C.onUnload(), B.onLoad(), B.onShow()
    D
    B
    D.onUnload(), C.onUnload(), B.onLoad(), B.onShow()
    D (Entered due to redirection)
    A
    D.onUnload(), A.onLoad(), A.onShow()
    D (Entered due to redirection)
    B
    D.onUnload(), B.onLoad(), B.onShow()
    Note:
    navigateTo and redirectTo can be used to open non-tabBar pages only.
    switchTab can be used to open tabBar pages only.
    reLaunch can be used to open any pages.
    The tabBar on the bottom of a page is determined by the page. In other words, tabBar is displayed on the bottom of all pages defined as tabBar.
    Parameters used to call page routing can be obtained via onLoad in the destination page.

    6. Modules

    6.1 Modularization

    Some common codes can be extracted to create an independent js file as a module. APIs for the module can be exposed only via module.exports or exports.
    Note:
    exports is a reference to module.exports. Therefore, a random modification to the point of exports in the module may cause an unknown error. Developers are advised to expose module APIs via module.exports if they do not know the relationship between them.
    Currently, node_modules cannot be directly passed into Mini Programs. To use node_modules, developers are advised to copy relevant code to the directory of the Mini Program, or use the npm feature supported by Mini Programs.
    // common.js
    function sayHello(name) {
    console.log(`Hello ${name} !`)
    }
    function sayGoodbye(name) {
    console.log(`Goodbye ${name} !`)
    }
    
    module.exports.sayHello = sayHello
    exports.sayGoodbye = sayGoodbye
    To pass common code into files that need to access these modules, use require.
    var common = require('common.js')
    Page({
    helloMINA: function() {
    common.sayHello('MINA')
    },
    goodbyeMINA: function() {
    common.sayGoodbye('MINA')
    }
    })

    6.2 File Scope

    Variables and functions declared in the JavaScript file are valid only in the file. Variables and functions with the same names can be declared in different files without affecting each other.
    The global application instance can be obtained via the global function getApp. To obtain the global data, you can set App(). For example:
    // app.js
    App({
    globalData: 1
    })
    // a.js
    // The localValue can only be used in file a.js.
    var localValue = 'a'
    // Get the app instance.
    var app = getApp()
    // Get the global data and change it.
    app.globalData++
    // a.js
    // The localValue can only be used in file a.js.
    var localValue = 'a'
    // Get the app instance.
    var app = getApp()
    // Get the global data and change it.
    app.globalData++
    Note:
    It's worth noting that require needs to use relative paths when introducing modules.

    7. API

    Mini Program development framework to provide rich micro-channel native API, you can easily tune up WeChat provides capabilities, such as access to user information, local storage, payment functions. Please refer to API Overview
    Usually, in Mini Programs API There are several types:

    7.1 Event monitor API

    We made a pact to on Initial API Used to listen if an event is triggered, such as:wx.onSocketOpen,wx.onCompassChange Wait.
    this kind API Accepts a callback function as a parameter that is called when an event is triggered, and passes in the relevant data as parameters.
    Code examples:
    wx.onCompassChange(function (res) {
    console.log(res.direction)
    })

    7.2 synchronization API

    We made a pact to Sync Ending API It's all in sync. API, Such as wx.setStorageSync,wx.getSystemInfoSync Wait. In addition, there are some other synchronization API, such as wx.createWorker,wx.getBackgroundAudioManager For details, see API Instructions in the documentation.
    synchronization API Can be obtained directly from the return value of the function, and an exception can be thrown if the execution goes wrong.
    Code examples
    try {
    wx.setStorageSync('key', 'value')
    } catch (e) {
    console.error(e)
    }

    7.3 asynchronous API

    Majority API It's all asynchronous. API, such as wx.request,wx.login Wait. this kind API Interfaces usually accept a Object Type, which supports specifying the following fields on demand to receive interface call results.
    Object Parameter specification
    Parameter name
    type
    Required
    Introductions
    success
    function
    no
    Interface calls the successful callback function
    fail
    function
    no
    Interface calls failed callback functions
    complete
    function
    no
    Callback function at the end of an interface call (both successful and unsuccessful calls are executed)
    Other
    Any
    -
    Additional parameters defined by the interface
    Parameters to the callback function
    success,fail,complete When the function is called, it passes in a Object Type parameter with the following fields:
    attribute
    type
    Introductions
    errMsg
    string
    Error message if the call returns successfully ${apiName}:ok
    errCode
    number
    Error code, partial only API Support, please refer to the corresponding meaning API Documentation, if successful 0。
    Other
    Any
    Interface to return additional data
    Code examples
    wx.login({
    success(res) {
    console.log(res.code)
    }
    })
    
    Contact Us

    Contact our sales team or business advisors to help your business.

    Technical Support

    Open a ticket if you're looking for further assistance. Our Ticket is 7x24 avaliable.

    7x24 Phone Support