Code Analysis of WeChat applets: 2. logic layer

Source: Internet
Author: User
Code parsing tutorial for applets: 2. logic layer,
This article mainly introduces three important functions in a applet: App () getApp () Page (), Page initialization, and data modularization.



App ()
The App () function is used to register a small program. An object parameter is used to specify the life cycle function of a applet.
Object parameter description:

Attribute Type Description Trigger Time
OnLaunch Function Life cycle function-listens to Applet initialization When the applet initialization is complete, onLaunch is triggered (only once globally)
OnShow Function Life cycle function-listener for applet display OnShow is triggered when the applet is started or enters the foreground display from the background.
OnHide Function Lifecycle functions-monitor hidden applets When a applet enters the background from the foreground, onHide is triggered.
Others Any Developers can add any function or data to the Object parameter, and use this to access


Foreground and background definitions:When the user clicks close in the upper left corner or presses the Home key of the device to exit, the applet is not destroyed but enters the background. when the applet is started again or opened again, it will also enter the foreground from the background.
Only when the applet enters the background for a certain period of time or the system resource usage is too high will it be destroyed.

// App. js App ({onLaunch: function () {// call the API to obtain 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 {// call the logon 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, ceshi: "I am global data "}})

Copy code
GetApp ()
We provide the global getApp () function to obtain the applet instance.

// other.js  var appInstance = getApp()  console.log(appInstance.globalData) // I am global data

Copy code
Note:
The App () must be registered in app. js and cannot be registered multiple.
Do not call getApp () in the function defined in App (). use this to get the app instance.
Do not call getCurrentPage () during onLaunch. the page is not yet generated.
Do not call the lifecycle function without permission after obtaining the instance through getApp.


Page
The Page () function is used to register a Page. An object parameter is used to specify the initial data, lifecycle function, and event processing function of the page.
Object parameter description:

Attribute Type Description
Data Object Initial page data
OnLoad Function Lifecycle function-listen to page loading
OnReady Function Lifecycle function-listener page rendering complete
OnShow Function Life cycle function-listener page display
OnHide Function Lifecycle functions-hide a listener page
OnUnload Function Life cycle function-uninstall the listener page
Others Any Developers can add any function or data to the Object parameter, and use this to access


Initialize data
The initialization data is used as the first page rendering. Data is transmitted from the logic layer to the rendering layer in JSON format. Therefore, the data must be in JSON format: string, number, Boolean value, object, and array.
The rendering layer can bind data through WXML.
Sample code:

 
  {{text}}
   
 
  {{array[0].msg}}
   Page({    data: {      text: 'init data',      array: [{msg: '1'}, {msg: '2'}]    }  })

Copy code
Event Processing Functions
In addition to initializing data and Lifecycle Functions, Page can also define some special functions: event processing functions. You can add event binding to the rendering layer. When an event is triggered, the event processing function defined in Page is executed.
Sample code:

 
   click me 
   Page({    viewTap: function() {      console.log('view tap')    }  })


Copy code
Page. prototype. setData ()
The setData function is used to send data from the logic layer to the view layer and change the value of this. data.
Note:

  • Modifying this. data directly is invalid, and the page status cannot be changed, resulting in data inconsistency.

  • Data set at a time cannot exceed KB. avoid setting too much data at a time..

SetData () parameter format
Accept an object and change the value corresponding to the key in this. data to value in the form of key and value.
The key can be very flexible and provided in the form of data paths, such as array [2]. message, a. B. c. d, and does not need to be pre-defined in this. data.
Sample code:

   
 
  {{text}}
    Change normal data   
 
  {{array[0].text}}
    Change Array data   
 
  {{obj.text}}
    Change Object data   
 
  {{newField.text}}
    Add new data   //index.js  Page({    data: {      text: 'init data',      array: [{text: 'init data'}],      object: {        text: 'init data'      }    },    changeText: function() {      // this.data.text = 'changed data'  // bad, it can not work      this.setData({        text: 'changed data'      })    },    changeItemInArray: function() {      // you can use this way to modify a danamic data path      var changedData = {}      var index = 0      changedData['array[' + index + '].text'] = 'changed data'      this.setData(changedData)    },    changeItemInObject: function(){      this.setData({        'object.text': 'changed data'      });    },    addNewField: function() {      this.setData({        'newField.text': 'new data'      })    }  })

Copy code
Modular
We can extract some public code into a separate js file as a module. The interface can be exposed only through module. exports.

// common.js  function sayHello(name) {    console.log('Hello ' + name + '!')  }  module.exports = {    sayHello: sayHello  }

Copy code

In files that need to use these modules, use require (path) to introduce public code.

var common = require('common.js')  Page({    helloMINA: function() {      common.sayHello('MINA')    }  })

Copy codeNext we will introduce the WXML of The View layer.

More code analysis for small programs: 2. articles related to the logic layer should be followed by PHP!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.