Author introduction: Pan Yifei, meituan Dianping engineer, 2 years of Web development experience, is now a member of meituan Dianping ordering team.

This article is connected with the public comment ordering applet development experience – view layer, this issue would like to share with you the public ordering ordering applet development logic layer experience.

Unlike the view layer, which wechat defines a set of WXML and WXSS corresponding to HTML, the logic layer of the small program is written in javascript. However, there are some differences with our ordinary writing JS. I’m going to explain it in practice. The logical layer code structure is

Menu ├── Menu.html ├─ menu.js ├─ menu.json ├─ menu.less app.js

As a logical layer we only need to focus on app.js and menu.js.

The App and Page

App

Applet provides the App method to register the entire applet. In the App method we can pass in an object specifying the applet’s life cycle function and custom functions or data. Note that this function can only be called once.

  • App
    • globalData
    • onLaunch
    • onShow
    • onHide
    • onError
    • Other Customizations

As shown above, the App has four life cycle functions. We can obtain some global information during launch, such as user information, store information and so on, and then store it into the global data. The data here can be accessed by each page.

Page

The applet provides Page functions for each Page. Most of the code for the entire logical layer is written in Page functions, which take over the entire Page’s data, lifecycle functions, and functions that trigger events bound in the view, such as click events. The arguments allowed for the entire Page function are as follows:

  • Page
    • data
    • onload
    • onReady
    • onShow
    • onHide
    • onUnload
    • onPullDownRefresh
    • onReachBottom
    • onShareAppMessage
    • Other custom functions

As mentioned above, the Page function has more life functions because it is at the Page level, there are pull-down refresh events, there are events when the Page reaches the bottom. Here we need to distinguish between the life cycle functions. OnLoad is called only once during initialization, onShow is called every time the page is opened, and onReady is called only when the page is first rendered. OnHide is called when navigateTo or bottom TAB is switched, onUnload is called when redirectTo or navigateBack is switched. Page for a more detailed rendering process, see the following image:

The view layer and the logical layer initialize the data at the same time. The view layer notifies the logical layer to send data when ready. The logical layer performs the onload and onShow methods, waits for notifications from the view layer, sends data to the view layer after receiving notifications from the view layer, and then continues to wait for notifications from the view layer. After rendering the data for the first time, the view layer notifies the logic layer that the rendering is complete and the logic layer calls the onReady method. Subsequent behavioral logic layers can then re-render the view layer by sending data again.

The entire workflow of Page can be seen in the following figure:


GetApp and getCurrentPages

Variables and functions declared in applets are valid only in that file. Different files can declare variables and functions with the same name without affecting each other. As mentioned above, global data can be set within the App. We can use the global function getApp() to get global reference instances in each Page. You can then access the data for the page. For example, when we return to the menu page after placing an order in the shopping cart, we may need to refresh the menu. We will call getApp().data.menurefresh = true on the shopping cart page, and then judge by the onShow method on the menu page, for example:

let app = getApp(); Page(requestMenu () {// Refresh menu}; onShow () { if (app.data.menuRefresh === true) { app.data.menuRefresh === false; this.requestMenu(); }});Copy the code

Within each Page, we can also use getCurrentPages to get an instance of the current Page stack, as an array, with the first element being the home Page and the last element being the current Page. The page stack looks like the following table:

routing Page stack representation
Initialize the New page is pushed
Open a new page New page is pushed
Page redirection The current page is out of the stack, and the new page is in the stack
The page returns The page keeps going off the stack until the target page is returned and a new page is pushed
The Tab to switch All pages are off the stack, leaving only new Tab pages

Note that we cannot manually modify the page stack, we can only analyze which wechat API is used to jump the page according to the page stack. The jump API is explained below.

modular

Module. Exports/commonJS module. Exports/commonJS module. Applets currently do not support importing node_modules, that is, they do not support third-party modules. When we need to use external dependencies, it is recommended to copy the code directly into the applets directory and import it through the require function in the relative path.

WeChat API

As an important function of wechat, the framework of wechat provides a very rich wechat native API, which can easily adjust the capabilities provided by wechat. In addition to some native components of the view layer, there are also some functional apis, such as scanning code, positioning, media playback, local storage and payment functions.

What we used this time was to initiate network requests through wechat and the data storage of wechat.

Send the request

Wechat provides wx.request to initiate a request. Note that this method initiates an HTTPS request. So before developing wechat small program, we have to move HTTPS~ when we use API, we also use the pinkie package to package request into the form of Promise for our convenience. It is important to note that the operating environment of wechat is not a browser and does not provide cookie function. However, to solve the problem of user identification, we need to bring the user’s token, which is generated by the back end and placed in the global data of App when the user logs in.

Data is stored

There is a large amount of menu data on our dianping ordering page, which was implemented on H5 using localStorage of the browser. This time switch to wechat storage, the cost is very small, use the adapter mode, the wechat data interface to adapt to the interface we need. This is also intended to slowly bring H5 and applets into the same code for future iterations.

navigation

Small program in order to reduce the user’s use of the trouble, the page path can only have a maximum of 5 layers, so we use the time to try to avoid multi-layer interaction.


const app = getApp(); module.exports = function go2Page(opts) { if (! opts) return; if (! opts.url) return; let url = opts.url; // Get the current page stack const history = getCurrentPages(); let path = url.split('? ') let params; if (path.length === 2) { params = path[1]; } let page = path[0].split('/').pop(); let index = -1; for (var i = 0; i < history.length; i++) { let hPath = history[i].__route__; let hPage = hPath.split('/').pop(); if (page == hPage) { index = i; break; NavigateTo ({url: url});}} if (index === -1) {wx.navigateTo({url: url}); } else {if (params) {//query = query(params); //query = query(params); } // Save the parameters of the page to the global data, and then can be retrieved from the page, store is declared by the app. Store (page, params); wx.navigateBack({ delta: history.length - (index + 1) }); }}Copy the code

Tip

Since the framework of the applet does not run in the browser, some of the capabilities of javascript on the Web side are not available, in addition to cookies mentioned above, document, window and so on. All of the developer’s code is eventually packaged into a single piece of javascript that runs when the applet is started until the applet is destroyed. This is similar to the browser ServiceWorker, so the logical layer is also called App Service.

This article was published on March 02, 2017. Please check for updates or fixesThe official documentation.

Reference: wechat applets developer documentation


Did this article help you? Welcome to join the front End learning Group wechat group: