【概】方法的封装对程序来说至关重要,不仅能减小程序体积,而且可以减轻工作量,节约不少时间。
【实例】1、权限的检查与请求(单个回调)
代码:写在Util.js内,需要在module.exports添加方法,如:
module.exports = {
formatTime: formatTime,
checkPermisson:checkPermisson,
getPermission: getPermission,
openSetting: openSetting,
getAddress:getAddress
}
/**检查是否获得权限 */
function checkPermisson(obj,callback) {
wx.getSetting({
success(res) {
if (!res.authSetting[obj]) {
return typeof callback == "function" && callback(false);
}else{
return typeof callback == "function" && callback(true);
}
}
})
}
/**获取权限 */
function getPermission(per){
wx.authorize({
scope: per,
success() {
return typeof callback == "function" && callback(true);
},fail(res){
console.log(res)
return typeof callback == "function" && callback(false);
}
})
}
述:本想通过checkPermisson一次性检查所有需要的权限是否添加,没有添加则弹出权限请求,但是小程序后因用户信息不能自动弹出请求,故检查权限与请求权限分开来,所以直接return true or false即可。
上述方法的使用:
//获取用户信息
util.checkPermisson("scope.userInfo", function (res) {
if (!res) {
console.log("未授权获取用户信息")
//显示用户信息权限请求
that.setData({
info_per:false
})
}else{
console.log("已经获取用户权限")
}
});
【实例】2、地理坐标的请求与获取地理位置描述(传递函数回调)
述:小程序中能通过小程序api获取设备的坐标,想要获取地理位置描述还得通过其他如:高德、腾旭、百度地图的api,所以获取描述的方法,先通过getAddress获取地理坐标,再获取位置描述
//腾讯地图api
var QQMapWX = require('./qqmap-wx-jssdk.min.js');
// 实例化API核心类
var demo = new QQMapWX({
key: 'RT2BZ-ZD2KK-C35JO-****-WZFLH-SYBKB' // 必填
});
/**获取地理坐标 */
function getAddress(callback){
wx.getLocation({
type: 'wgs84',
success(res) {
const latitude = res.latitude
const longitude = res.longitude
return retrunAddress(latitude, longitude,callback);
}
})
}
/**根据坐标获得位置描述 */
function retrunAddress(latitude,longitude,callback){
demo.reverseGeocoder({
location: {
latitude: latitude,
longitude: longitude
},
success: function (res) {
},
fail: function (res) {
console.log(res);
},
complete: function (res) {
console.log(res);
return typeof callback == "function" && callback(res);
}
})
方法的使用:
//获取用户地理位置
util.checkPermisson("scope.userLocation", function (res) {
if (res) {
// console.log("以获取位置")
util.getAddress(function (callback){
// console.log(callback)
var add = callback.result.address_component.district + callback.result.address_component.street_number;
var mHeader = that.data.header;
mHeader.address = add;
// console.log(mHeader)
that.setData({
header:mHeader
})
})
} else {
util.getPermission("scope.userLocation",function (res){
if(!res){
wx.showToast({
title: '请打开设置页面',
})
util.openSetting()
}else{
}
});
}
})