Code analysis of WeChat applet: 2. Logic layer

高洛峰
Release: 2017-03-02 13:12:35
Original
1757 people have browsed it


This article mainly introduces the three important functions App()getApp()Page() in the WeChat applet, as well as the initialization of the page , data modularization function.




##App()
App() function is used to register a small program. Accepts an object parameter, which specifies the life cycle function of the applet, etc.
object parameter description:

AttributesTypeDescriptionTrigger timingonLaunch FunctionLife cycle function--listen to the initialization of the appletWhen the initialization of the applet is completed, onLaunch will be triggered (only triggered once globally) onShowFunctionLife cycle function--listening to the mini program displayWhen the mini program starts, or enters the foreground display from the background, onShow will be triggered onHideFunctionLife cycle function--listening to the mini program hidingWhen the mini program enters the background from the foreground, onHide will be triggeredOthersAnyDevelopers can add any function or data to the Object parameter, which can be accessed using this


Foreground and background definition: When the user clicks the upper left corner to close, or presses the device Home When you press the key to leave WeChat, the mini program is not being destroyed, but enters the background; when you start WeChat again or open the mini program again, it will enter the foreground from the background.
Only when the mini program enters the background for a certain period of time, or the system resource usage is too high, will it be truly destroyed.

//app.js  
App({  
  onLaunch: function () {  
    //调用API从本地缓存中获取数据  
    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{  
      //调用登录接口  
      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 after login

Copy code
getApp()
We provide the global getApp() function, which can be obtained Mini program example.

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

Copy code
Note:
##App()must be in app.js Register, and you cannot register more than one.
Do not define it in App()# Call #getApp() in the function inside , use this# then you can get the app instance.
Don’t call getCurrentPage(), the page has not been generated yet.
After obtaining the instance through getApp, do not call the life cycle function privately.

##Page

##Page()# function is used to register a page. Accepts an object parameter, which specifies the initial data, life cycle function, event processing function, etc. of the page.
object parameter description:

Properties

TypeObjectFunctionFunctionFunctionFunctionFunctionAny
Descriptiondata
Page Initial dataonLoad
Life cycle function--listen to page loadingonReady
Life cycle function--listen to the completion of page renderingonShow
Life cycle Function--Listening page displayonHide
Life cycle function--Listening page hidingonUnload
Life cycle function--listen for page unloadingOthers
Developers can add any function or data to the Object parameter, which can be accessed using this


初始化数据
初始化数据将作为页面的第一次渲染。data将会以JSON的形式由逻辑层传至渲染层,所以其数据必须是可以转成JSON的格式:字符串,数字,布尔值,对象,数组。
渲染层可以通过WXML对数据进行绑定。
示例代码:

<view>{{text}}</view>  
<view>{{array[0].msg}}</view>  
Page({  
  data: {  
    text: &#39;init data&#39;,  
    array: [{msg: &#39;1&#39;}, {msg: &#39;2&#39;}]  
  }  
})
Copy after login

复制代码
事件处理函数
除了初始化数据和生命周期函数,Page中还可以定义一些特殊的函数:事件处理函数。在渲染层可以在组件中加入事件绑定,当达到触发事件时,就会执行Page中定义的事件处理函数。
示例代码:

<view bindtap="viewTap"> click me </view>  
Page({  
  viewTap: function() {  
    console.log(&#39;view tap&#39;)  
  }  
})
Copy after login


复制代码
Page.prototype.setData()
setData函数用于将数据从逻辑层发送到视图层,同时改变对应的this.data的值
注意:

  • 直接修改this.data无效,无法改变页面的状态,还会造成数据不一致。

  • 单次设置的数据不能超过1024kB,请尽量避免一次设置过多的数据

setData()参数格式
接受一个对象,以key,value的形式表示将this.data中的key对应的值改变成value。
其中key可以非常灵活,以数据路径的形式给出,如array[2].messagea.b.c.d,并且不需要在this.data中预先定义。
示例代码:

<!--index.wxml-->  
<view>{{text}}</view>  
<button bindtap="changeText"> Change normal data </button>  
<view>{{array[0].text}}</view>  
<button bindtap="changeItemInArray"> Change Array data </button>  
<view>{{obj.text}}</view>  
<button bindtap="changeItemInObject"> Change Object data </button>  
<view>{{newField.text}}</view>  
<button bindtap="addNewField"> Add new data </button>  
//index.js  
Page({  
  data: {  
    text: &#39;init data&#39;,  
    array: [{text: &#39;init data&#39;}],  
    object: {  
      text: &#39;init data&#39;  
    }  
  },  
  changeText: function() {  
    // this.data.text = &#39;changed data&#39;  // bad, it can not work  
    this.setData({  
      text: &#39;changed data&#39;  
    })  
  },  
  changeItemInArray: function() {  
    // you can use this way to modify a danamic data path  
    var changedData = {}  
    var index = 0  
    changedData[&#39;array[&#39; + index + &#39;].text&#39;] = &#39;changed data&#39;  
    this.setData(changedData)  
  },  
  changeItemInObject: function(){  
    this.setData({  
      &#39;object.text&#39;: &#39;changed data&#39;  
    });  
  },  
  addNewField: function() {  
    this.setData({  
      &#39;newField.text&#39;: &#39;new data&#39;  
    })  
  }  
})
Copy after login

复制代码
模块化
我们可以将一些公共的代码抽离成为一个单独的js文件,作为一个模块。模块只有通过module.exports才能对外暴露接口。

// common.js  
function sayHello(name) {  
  console.log(&#39;Hello &#39; + name + &#39;!&#39;)  
}  
module.exports = {  
  sayHello: sayHello  
}
Copy after login

复制代码

在需要使用这些模块的文件中,使用require(path)将公共代码引入。

var common = require(&#39;common.js&#39;)  
Page({  
  helloMINA: function() {  
    common.sayHello(&#39;MINA&#39;)  
  }  
})
Copy after login

复制代码下一篇我们会介绍视图层的WXML。

更多微信小程序之代码解析:二.逻辑层 相关文章请关注PHP中文网!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template