(3) : the introduction of Rx, plug in the wings for small programs

Very early registered micro channel small program internal test, because is late procrastination patients, so has not learned. Until yesterday (December 28, 2016), Zhang Xiaolong announced that micro channel small program on January 9, 2017 officially launched, the screen is full of small program news. That’s when I realized, I can’t just pay 300 yuan for nothing. I have to learn.

Anyway, learning has to be summarized, so it’s better to write a tutorial from scratch. In other words, there must be a lot of mistakes in learning now and selling now. Cut the crap, we start, first download WeChat small program development tools mp.weixin.qq.com/debug/wxado… Choose your own platform to download and install.

Wechat applets development tool download page

I won’t talk about the process of registering the sequence number (there are a lot of such tutorials on the Internet, I don’t need to spend time here). If you want to develop, you’d better apply for one through the company. When you first start the development tool, scan the code and select add a project with no appId. What project should I do? I don’t have any idea, so LET’s bring Todo out first. Let’s implement a wechat applet version of Todo, also with HTTP background version. Why Todo? Because its logic is relatively complete, add, delete, change and check, HTTP request, return complete. In a platform to understand this app can basically start to work, this product is simply the new era of Hello World ah.

File structure

When creating a project, the default development tool generates a sample for us. Let’s see what this example is. On the left side of the developer tool is a preview, and in the middle is the file directory. It’s easy to see the directory structure:

The development tool automatically helps generate a sample project

Global file

Take a look at the root directory: there are three files app.js, app.json and app.wxss in this directory. App.js is an Application entry that defines the app () function that registers a small Application, just like Application on Android and Angular2. Accepts an object parameter that specifies the life cycle function of the applet, etc.

//app.js
App({
  onLaunch: function () {
    // Call the API to fetch data from the local cache
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
  },
  getUserInfo:function(cb){
    var that = this
    if(this.globalData.userInfo){
      typeof cb == "function" && cb(this.globalData.userInfo)
    }else{
      // Invoke the login interface
      wx.login({
        success: function () {
          wx.getUserInfo({
            success: function (res) {
              that.globalData.userInfo = res.userInfo
              typeof cb == "function" && cb(that.globalData.userInfo)
            }
          })
        }
      })
    }
  },
  globalData: {userInfo:null}})Copy the code

A few things can be seen from the simple code above:

  • App() is a function in itself, and you can get an instance of the application from the system-provided getApp() on other pages.
  • OnLaunch is a lifecycle function that is triggered (only once) when the applet initialization is complete. Here a date is written to local storage during application initialization.
  • GlobalData is the globalData storage area, and the sample code only places one userInfo as a global variable.
  • The example code defines a global method getUserInfo here, which can be accessed via getApp().getUserInfo(). If you turn it onpages/index/index.jsYou’ll notice that the sample code calls the getUserInfo global method after getting the application instance from getApp()
// Get the application instance
const app = getApp()
...
// Call the application instance method to get global data
app.getUserInfo(function(userInfo){
  // Update data
  that.setData({
    userInfo:userInfo
  })
})Copy the code

So what are some lifecycle functions like onLaunch? There’s also onShow, onHide and onError. OnShow and onHide are called when the application switches from background to foreground and from foreground to background, respectively. When you close the small program or switch the wechat app to another app, wechat does not directly kill the small program, the small program just goes into the background, when you switch back, the small program goes into the foreground again. This mechanism is similar to app switching on Android and iOS. OnError, as the name implies, is raised when a script error or API call failure occurs in a small program. Note: Do not call life cycle functions on other pages

Let’s look at app.json, which is the applet’s global configuration file. The structure is also very simple: Pages defines the file path of the page, window defines some elements of the entire window of the small program, such as Title text, Title color, window background color and so on.

{
  "pages": ["pages/index/index"."pages/logs/logs"]."window": {"backgroundTextStyle":"light"."navigationBarBackgroundColor": "#fff"."navigationBarTitleText": "todos"."navigationBarTextStyle":"black"
  },
  "debug": true
}Copy the code

For example, in the configuration above, the window would look like this

How the window behaves in the default configuration

What would happen if we changed app.json to look like this?

{
  "pages": ["pages/index/index"."pages/todos/todos"]."window": {"backgroundTextStyle":"light"."navigationBarBackgroundColor": "# 000"."navigationBarTitleText": "todo"."navigationBarTextStyle":"white"."backgroundColor": "#492b2b"
  },
  "debug": true
}Copy the code

The effect of changing app.json

Well, the navigation background is black, the text is white, everything is perfect. We also added a “backgroundColor”: “#492b2b”. After you click the profile picture to enter the log page, click the upper left corner to return to see an animation, the background of the animation is actually the window background color we set! ?

BackgroundColor is displayed when the interface is switched

I guess it’s because the Page is in front of the background, but it’s not. Let’s test that out. To verify this, we add a “enablePullDownRefresh”: “true” to the window Settings. This is a switch that activates the pull-down refresh effect.

Pull down to reveal window background color

Similarly, backgroundTextStyle defines the style of drop-down background font and loading diagram (dark/light only).

In this configuration file, we can also define a TAB bar for switching interfaces, so let’s try it out.

{
  "pages": ["pages/index/index"."pages/todos/todos"]."window": {"backgroundTextStyle":"light"."navigationBarBackgroundColor": "# 000"."navigationBarTitleText": "todo"."navigationBarTextStyle":"white"."backgroundColor": "#492b2b"."enablePullDownRefresh": "true"
  },
  "tabBar": {
    "list": [{
      "pagePath": "pages/index/index"."text": "Home page"
    }, {
      "pagePath": "pages/logs/logs"."text": "Log"}},"debug": true
}Copy the code

Effect after tabBar is configured

Yeah, it’s ugly, but it shows. So, how do you customize this tabBar? In addition to the List attribute, it also provides color, selectedColor, backgroundColor, borderStyle, and postion attributes. Let’s set it all up

"TabBar ": {"pagePath": [{"pagePath": "pages/index/index", "text":" 页", "selectedIconPath": "Assets /images/home.png"}, {"pagePath": "pages/logs/logs", "text":" log ", "iconPath": "assets/images/log.png" }], "color": "#b0bec5", "backgroundColor": "#2196F3", "selectedColor": "#fff", "borderStyle": "#F8BBD0", "position": "bottom" }Copy the code

Custom tabBar effects

Still ugly, code farmer and straight male, can only make ends meet. You might notice that I’ve added selectedIconPath and iconPath to the list. Actually, I’m just lazy. I don’t want to find two more pictures. If the home page is TAB by default, both ICONS will be displayed.

In addition to tabBar, you can also set a debug property, which is false by default. If set to true, you will see a lot of logs displayed on the console during debugging. Its information has Page registration, Page routing, data update, event trigger and so on. This switch is recommended to be turned on during development and turned off during release.

Debug set to true displays a lot of log information on the console

As you can probably guess, app.wxss is a CSS style sheet. This global style is available to all pages.

/**app.wxss**/
.container {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  padding: 200rpx 0;
  box-sizing: border-box;
}Copy the code

For someone like me, I’m going to have to play around with this CSS and see what it does. Let’s start with a background color, red, background-color: red; .

Changes to the home page

There is an area at the bottom of the home page that is not colored.

Changes on the log page

This variation means that the Container selector is applied to the page and the height is determined by the content of the page, so the 100% won’t fill the full screen. Fortunately, wechat applet can accept most of the CSS Settings, if the height: 100%; To height: 100 vh; I can fill the full screen.

Page file

Page files are also very simple, basically.js,.json,.wxss files with the same name as the folder, the only additional type is.wxml files. The.js file defines a Page function that builds the logic of the Page view, while.wxml describes the structure and layout of the Page view. First take a look at index.js:

var app = getApp()
Page({
  data: {
    motto: 'Hello World'.userInfo: {}},// Event handlers
  bindViewTap: function() {
    wx.navigateTo({
      url: '.. /logs/logs'})},onLoad: function () {
    console.log('onLoad')
    var that = this
    // Call the application instance method to get global data
    app.getUserInfo(function(userInfo){
      // Update data
      that.setData({
        userInfo:userInfo
      })
    })
  }
})Copy the code

You can see from the above structure that basically the Page function is of this form. It takes an object consisting of lifecycle functions, event handlers, and data objects. That is, the code above can be rewritten to look like this.

let app = getApp()
let pageParams = {
  data: {
    motto: 'Hello World'.userInfo: {}},// Event handlers
  bindViewTap: function() {
    wx.navigateTo({
      url: '.. /logs/logs'})},onLoad: function () {
    console.log('onLoad')
    var that = this
    // Call the application instance method to get global data
    app.getUserInfo(function(userInfo){
      // Update data
      that.setData({
        userInfo:userInfo
      })
    })
  }
}
Page(pageParams)Copy the code

In fact, we prefer to write this way because it allows us to avoid too much nesting and more flexibility with pageParams. Pageparams. data = blablabla or pageparams. onLoad = someFunctionCall. By the way, I don’t know what the name of this object is, it’s just my name, but the Page function needs such an argument anyway.

So what are the built-in functions of the page? You can refer to the following table, where the first five items are life cycle functions.

Built-in functions role Invocation mechanism
onLoad Listening for page loading Called once during the life cycle
onReady The listener page is rendered for the first time Called once during the life cycle
onShow Monitor page display This is called every time the page is opened
onHide Listening page hiding Called when navigateTo or bottom TAB is switched
onUnload Listening page uninstallation Called when redirectTo or navigateBack is available
onPullDownRefresh Monitor user pull down actions User action trigger
onReachBottom A handler for a pull-down event on the page Events trigger
onShareAppMessage Users click on the upper right to share User click trigger

For details, please refer to the schematic diagram of page life cycle provided by wechat official documents

Schematic diagram of page life cycle given in official wechat document

Take a look at index.wxml, which is actually a template file similar to HTML, but it’s not clear why wechat recreated the wheel itself. Here class=”container” applies our global style.

<! --index.wxml-->
<view class="container">
  <view  bindtap="bindViewTap" class="userinfo">
    <image class="userinfo-avatar" src="{{userInfo.avatarUrl}}" background-size="cover"></image>
    <text class="userinfo-nickname">{{userInfo.nickName}}</text>
  </view>
  <view class="usermotto">
    <text class="user-motto">{{motto}}</text>
  </view>
</view>Copy the code

Event binding is done by adding bindXXX=handler to the component tag, which needs to be defined in the pageParams object. {{userinfo.nickname}} is a property that references the data object we defined in index.js.

Json is a simple way to set some properties of the page, for example:

{
    "navigationBarTitleText": "Home page"
}Copy the code

The navigation text becomes the value we set.

Set the navigation text

Ok, by now we should have a general understanding of the basics of wechat apps. In the next video we’re going to try Todo our Todo application.