微信小程序 闭包写法详细介绍
微信小程序闭包写法
在入口处的app.js中定义了一个获取用户OpenId的函数,在微信的登录接口wx.login中发起网络请求。这个函数传入一个回调函数cb
getOpenIdData:function(cb){ varthat=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("requesterror") } }) } }) }
在index.js文件时,使用getOpenIdData接口
varapp=getApp() app.getOpenIdData(function(openid){ //回调更新数据 that.setData({ openid:openid }) })
在接口中传入匿名函数
function(openid){ //回调更新数据 that.setData({ openid:openid }) }
先将匿名函数传入到app.js中,获取到openid数据。再回到index.js将数据赋给此文件的全局变量。这样就实现跨文件传递数据。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!