找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索本站精品资源

首页 教程频道 小程序开发 查看内容

微信小程序中的闭包写法

作者:模板之家 2018-1-31 11:55 90人关注

在入口处的 app.js 中定义了一个获取用户 OpenId 的函数,在微信的登录接口 wx.login 中发起网络请求。这个函数传入一个回调函数 cb getOpenIdData: function ( cb ) { var that = this //调用登录接口

在入口处的 app.js 中定义了一个获取用户 OpenId 的函数,在微信的登录接口 wx.login 中发起网络请求。这个函数传入一个回调函数 cb

getOpenIdData: function(cb) {
    var that = this
    //调用登录接口
    wx.login({
        success: function(res) {
            wx.request({
                url: 'https://api.weixin.qq.com/sns/jscode2session',
                data: {
                    appid: "wx6224eb*********",
                    secret: "879b58fc64bc5**************",
                    js_code: res.code,
                    grant_type: "authorization_code"
                },
                success: function(res) {
                    // 保存到全局变量中
                    that.globalData.openid = res["data"]["openid"]
                    cb(that.globalData.openid)
                },
                fail: function() {
                    console.log("request error")
                }
            })
        }
    })
}

在 index.js 文件时,使用 getOpenIdData 接口

var app = getApp()
app.getOpenIdData(function(openid){
    //回调更新数据
    that.setData({
    openid: openid
    })
})

在接口中传入匿名函数

function(openid){
    //回调更新数据
    that.setData({
    openid: openid
    })
}

先将匿名函数传入到 app.js 中,获取到 openid 数据。再回到 index.js 将数据赋给此文件的全局变量。这样就实现跨文件传递数据。


路过

雷人

握手

鲜花

鸡蛋
原作者: 模板之家 来自: 网络收集

全部回复(0)