微信小程序页面通信
时间:2020-03-14 18:13:25
收藏:0
阅读:74
1.新建一个js页面 event.js,里面放三个调用函数,并把这三个函数暴露出去
function on(event, fn, ctx) { if (typeof fn != "function") { console.error(‘fn must be a function‘) return } this._stores = this._stores || {} ; (this._stores[event] = this._stores[event] || []).push({ cb: fn, ctx: ctx }) } function emit(event) { this._stores = this._stores || {} var store = this._stores[event], args if (store) { store = store.slice(0) args = [].slice.call(arguments, 1) for (var i = 0, len = store.length; i < len; i++) { store[i].cb.apply(store[i].ctx, args) } } } function off(event, fn) { this._stores = this._stores || {} // all if (!arguments.length) { this._stores = {} return } // specific event var store = this._stores[event] if (!store) return // remove all handlers if (arguments.length === 1) { delete this._stores[event] return } // remove specific handler var cb for (var i = 0, len = store.length; i < len; i++) { cb = store[i].cb if (cb === fn) { store.splice(i, 1) break } } return } module.exports = { on: on, emit: emit, off: off }
2.app.js中引用这个js文件
const Event = require(‘/pages/event‘)
App({
event: Event,
3.主页面注册监听
onLoad() { app.event.on(‘afterPaySuccess‘, this.afterPaySuccess, this) }, afterPaySuccess: function (orderId) { // 如果index为1输出orderid的Value if(orderId.index===1){ console.log("输出1"+orderId.value ) }else{ console.log("输出不是1" ) } },
4.副页面发送数据,主页面收到数据
var data1 = [0xAE, 5, 9, 0x07] var mydata = { index: 1, value: data1 } app.event.emit(‘afterPaySuccess‘, mydata)
看网上大神的日志,不喜勿喷
评论(0)