tencent cloud

Feedback

Logic layer description

Last updated: 2024-03-05 14:38:08

    Logic layer (App service)

    The logical layer of the mini program development framework employs a JavaScript engine to provide a runtime environment for the developer's JavaScript code, as well as the unique features of the TMF mini program.
    The logical layer processes data and transmits it to the view layer, while simultaneously receiving event feedback from the view layer.
    All code written by developers will ultimately be packaged into a single JavaScript file, which runs at the launch of the mini program and continues until the mini program is terminated. This behavior is similar to ServiceWorker, hence the logical layer is also referred to as the App Service.
    Building upon the foundation of JavaScript, we have incorporated additional features to facilitate the development of mini programs:
    We have incorporated App and Page methods to facilitate the registration of programs and pages.
    We have introduced the getApp and getCurrentPages methods, which are used to retrieve the App instance and the current page stack, respectively.
    We offer a wealth of API options, such as TMF user data, scan code, payment, and other unique TMF capabilities.
    Each page possesses an independent scope and provides modularization capabilities.
    Note:
    The logic layer of the mini program framework does not operate within a browser, hence certain JavaScript capabilities available in the web, such as window and document, cannot be used.

    Register a mini program app

    App(Object)

    The App() function is used to register a mini-program. It accepts an Object parameter, which designates the lifecycle callbacks of the mini-program, among other things.
    App() must be invoked within app.js. It must be called only once, otherwise unforeseen consequences may occur.
    Explanation of the Object parameter:
    Attribute
    Type
    Description
    Trigger Timing
    function
    Lifecycle Callback - Monitor Mini Program Initialization Page Unload
    Upon completion of the mini program initialization (triggered only once globally)
    function
    Lifecycle Callback - Monitor the Initial Display of Mini Program
    Upon the launch of the mini program, or when it transitions from the backend to the frontend display.
    function
    Lifecycle Callback - Monitor the Initial Concealment of Mini Programs
    When the mini program transitions from the frontend to the backend.
    onError
    function
    Error listener function
    Triggered when the mini program encounters script error, or when an API call fails, accompanied by error information.
    function
    Page Non-existence Listener Function
    The function is triggered and called back with page information when the page the mini program intends to open does not exist.
    Other
    any
    Developers can add any function or data to the Object parameter, which can be accessed using this.
    -
    Frontend and Backend Definitions: When the user clicks the top right corner's close button, or presses the device's Home button to leave the host App, the mini program is not directly terminated, but instead enters the backend. When re-entering the host App or reopening the mini program, it will move from the backend to the frontend.
    Note:
    The mini program will only be truly terminated when it has been in the backend for a certain period of time, or when the system resource usage is excessively high.
    Closing the Mini Program: When a user enters the mini program through entrances such as Scan and Share (Scene Value is 1007, 1008, 1011, 1025), and exits without pinning the mini program, the mini program will be terminated.
    Sample Code
    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'
    })

    onLaunch(Object)

    Triggered when the mini program initialization is complete, it only triggers once globally. Parameter can also be obtained using getLaunchOptionsSync.
    Parameter and Description: Consistent with getLaunchOptionsSync .

    onShow(Object)

    Triggered when the mini program is launched, or when it transitions from the backend to the frontend display.

    onHide()

    Triggered when the mini program transitions from the frontend to the backend.

    onError(String error)

    Triggered when the mini program encounters a script error or an API call error. You can also bind a listener function using onError.
    Parameter and Description: Consistent with onError.

    onPageNotFound(Object)

    Triggered when the page the mini program intends to open does not exist.
    Sample Code
    App({
    onPageNotFound(res) {
    wx.redirectTo({
    url: 'pages/...'
    }) // If it's a tabbar page, use wx.switchTab.
    }
    })

    getApp(Object)

    The global getApp() function can be used to obtain the mini program's App instance.
    Explanation of the Object parameter:
    Field
    Type
    Description
    Earliest Version
    allowDefault
    boolean
    Returns the default implementation when the App is undefined. When the App is invoked, the attributes defined in the default implementation will be overridden and merged into the App.
    -
    Sample Code
    // other.js
    const appInstance = getApp()
    console.log(appInstance.globalData) // I am global data
    Note:
    Avoid invoking getApp() within functions defined in App(). The app instance can be accessed using this.
    After obtaining the instance through getApp(), refrain from invoking lifecycle functions privately.

    Scene Value

    Get scene value

    The currently supported scene values are:
    For mini programs, the aforementioned scene values can be obtained in App's onLaunch and onShow, or through getLaunchOptionsSync.

    Return source information scene

    In certain scenarios, it is also possible to obtain the originating application, WeChat Official Account, or mini program's appId.
    Scene Value
    Scene
    Significance of appId
    1020
    List of related mini programs on the We Chat Official Account profile page.
    Originating from We Chat Official Account
    1035
    Custom menu of We Chat Official Account
    Originating from We Chat Official Account
    1036
    App message sharing card
    Originating from App
    1037
    Mini program opening another mini program
    Originating from mini program
    1038
    Returning from another mini program
    Originating from mini program
    1043
    We Chat Official Account template message.
    Originating from We Chat Official Account
    Note:
    Due to the constraints of the Android system, it is currently impossible to obtain the scene value of exiting to the desktop by pressing the Home key and then re-entering the mini program from the desktop. In such cases, the previous scene value will be retained.

    Registration page

    For operations related to the registration page, see Registration Page.

    Page routing

    In the mini program, the routing of all pages is managed entirely by the framework.

    Page stack

    The framework maintains all current pages in the form of a stack. When a route switch occurs, the page stack behaves as follows:
    Routing method
    Page stack behavior
    Initialization
    New page enters the stack
    Opening the page
    New page enters the stack
    Page redirection
    Current page enters the stack, new page enters the stack
    Page return
    Pages continuously pop from the stack until the target return page is reached.
    Tab switching
    All pages pop from the stack, leaving only the new Tab page.
    Reload
    All pages pop from the stack, leaving only the new page.

    getCurrentPages()

    The getCurrentPages() function is used to obtain instances of the current page stack, presented in array format in accordance with the stack order. The first element represents the home page, while the last element signifies the current page.
    Note:
    Do not attempt to modify the page stack, as it may result in routing and page status errors.
    Avoid invoking getCurrentPages() during the App.onLaunch phase, as the page has not yet been generated at this point.

    Routing method

    The triggering methods for routing and the lifecycle functions of the page are as follows:
    Routing method
    Trigger Timing
    Pre-routing page
    Post-routing page
    Initialization
    The first page opened by the mini program.
    -
    onLoad, onShow
    Opening the page
    Invoke the API wx.navigateTo or use the component <navigator open-type="navigateTo"/>.
    onHide
    onLoad, onShow
    Page redirection
    Invoke the API wx.redirectTo or use the component <navigator open-type="redirectTo"/>.
    onUnload
    onLoad, onShow
    Page return
    Invoke the API wx.navigateBack, use the component <navigator open-type="navigateBack">, or the user presses the return button in the top left corner.
    onUnload
    onShow
    Tab switching
    Invoke the API wx.switchTab, utilize the component <navigator open-type="switchTab"/>, or the user switches the Tab.
    -
    For various scenarios, see the table below.
    Restart
    Invoke the API wx.reLaunch or use the component <navigator open-type="reLaunch"/>.
    onUnload
    onLoad, onShow
    The lifecycle corresponding to Tab switching (for instance, A and B are Tabbar pages, C is a page opened from A, and D is a page opened from C):
    The current page
    Post-routing page
    Triggered lifecycle (in order)
    A
    A
    Nothing happend
    A
    B
    A.onHide(), B.onLoad(), B.onShow()
    A
    B (Reopened)
    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 via forwarding)
    A
    D.onUnload(), A.onLoad(), A.onShow()
    D (Entered via forwarding)
    B
    D.onUnload(), B.onLoad(), B.onShow()
    Note:
    The navigateTo and redirectTo functions can only open non-TabBar pages.
    The switchTab feature can only open TabBar pages.
    The reLaunch function can open any page.
    The tabBar at the bottom of the page is determined by the page itself, meaning that any page defined as a tabBar page will have a tabBar at the bottom.
    The parameters carried by the page route can be obtained in the onLoad of the target page.

    File Scope

    Variables and functions declared within a JavaScript file are only valid within that file; identical variable and function names can be declared in different files without mutual interference.
    The global function getApp() can be used to obtain the global application instance. If global data is required, it can be set within the App() function, for example:
    // app.js
    App({
    globalData: 1
    })
    // a.js
    // The localValue can only be used in file a.js.
    const localValue = 'a'
    // Get the app instance.
    const app = getApp()
    // Get the global data and change it.
    app.globalData++
    // b.js
    // You can redefine localValue in file b.js, without interference with the localValue in a.js.
    const localValue = 'b'
    // If a.js it run before b.js, now the globalData shoule be 2.
    console.log(getApp().globalData)

    Modularization

    Common code can be extracted into a separate js file to serve as a module. The module can only expose its interface to the outside world through module.exports or exports.
    It is important to note that:
    exports 
    Currently, mini programs do not support direct import of
    // common.js
    function sayHello(name) {
    console.log(Hello ${name} !)
    }
    function sayGoodbye(name) {
    console.log(Goodbye ${name} !)
    }
    
    module.exports.sayHello = sayHello
    exports.sayGoodbye = sayGoodbye
    In files where these modules are needed, use
    const common = require('common.js')
    Page({
    helloMINA() {
    common.sayHello('MINA')
    },
    goodbyeMINA() {
    common.sayGoodbye('MINA')
    }
    })
    Note:
    require currently does not support absolute paths.

    API

    Monitor events

    It is agreed to use APIs starting with "on" to monitor event triggers, such as wx.onCompassChange, etc.
    These types of APIs accept a callback function as a parameter. When an event is triggered, this callback function is invoked, and the relevant data is passed in as parameters.
    Sample Code
    wx.onCompassChange(function (res) {
    console.log(res.direction)
    })

    Synchronous

    We have agreed that APIs ending with Sync are synchronous APIs, such as wx.setStorageSync, wx.getSystemInfoSync, etc. In addition, there are some other synchronous APIs. For more details, see relevant descriptions in the API documentation.
    The execution result of synchronous APIs can be directly obtained through the function return value. If an error occurs during execution, an exception will be thrown.
    Sample Code
    try {
    wx.setStorageSync('key', 'value')
    } catch (e) {
    console.error(e)
    }

    Async

    Most APIs are asynchronous, such as wx.request, wx.login, etc. These types of API interfaces typically accept an Object type parameter, which supports specifying the following fields as needed to receive the results of the interface call:
    Explanation of the Object parameter
    Field
    Type
    Required
    Description
    success
    function
    No
    Callback Function of Successful Interface Call
    fail
    function
    No
    Callback Function of Successful Interface Call
    complete
    function
    No
    Callback function executed upon the completion of the interface invocation (both successful and unsuccessful invocations)
    Other
    any
    -
    Other parameters defined by the interface
    Parameter of the callback function
    Upon invocation, the success, fail, and complete functions will receive an Object type parameter, containing the following fields:
    Attribute
    Type
    Description
    errMsg
    string
    Error information, which returns ${apiName}:ok if the invocation is successful
    errCode
    number
    Error code, supported only by certain APIs. For specific meanings, see the corresponding API documentation. The code is 0 in case of success.
    Other
    any
    Other data returned by the interface
    Sample Code
    wx.login({
    success(res) {
    console.log(res.code)
    }
    })

    WXS

    For operations related to WXS, see WXS Details.
    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