EventChannel

优质
小牛编辑
125浏览
2023-12-01

EventChannel

页面间事件通信通道

方法

EventChannel.emit(string eventName, any args)

触发一个事件

参数

string eventName

事件名称

any args

事件参数

EventChannel.on(string eventName, EventCallback fn)

持续监听一个事件

参数

string eventName

事件名称

function fn

事件监听函数

参数
any args

触发事件参数

EventChannel.once(string eventName, EventCallback fn)

监听一个事件一次,触发后失效

参数

string eventName

事件名称

function fn

事件监听函数

参数
any args

触发事件参数

EventChannel.off(string eventName)

取消监听一个事件。

参数

string eventName

事件名称

示例代码

//eventChannel-A.js
Page({
  navigateTo(url){
    jd.navigateTo({
      url:"../eventChannel-B/eventChannel-B",
      events: {
        // 为指定事件添加一个监听器,获取被打开页面传送到当前页面的数据
        eventA: function(data) {
          console.info(' 页面A接收到消息 navigate 内容为: ',data)
        }
      },
      success: ((res) =>{
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('eventB', { data: ' 这是页面A发送的消息 navigate '})
      })

    })
  }
})

//eventChannel-B.js
Page({
  eventChannel : null,
  onLoad: function(option){
    this.eventChannel = jd.getOpenerEventChannel();
  },
  callbackOnceB(data){
    console.info(' 页面B用 once 接收消息 内容为: ',data)
  },
  callbackOnB(data){
    console.info(' 页面B用 on 接收消息 内容为: ',data)
  },
  emitA(){
    this.eventChannel.emit('eventA', {data: ' 这是B页面发送的消息 Button'});
  },
  onB(){
    this.eventChannel.on('eventB',this.callbackOnB);
  },
  onceB(){
    this.eventChannel.once('eventB',this.callbackOnceB);
  },
  offAllB(){
    this.eventChannel.off('eventB');
  }
})