EventSourceTask.onMessage
收藏我的收藏
基础库 3.35.0 开始支持本方法,这是一个同步方法。
监听 EventSource 服务器发送信息的事件。
| 前提条件 | 无 |
| 业务背景 | 无 |
| 使用限制 | 无 |
| 注意事项 | 无 |
| 支持沙盒 | 否 |
| 相关教程 | 无 |
语法
EventSourceTask.onMessage(callback)
参数说明
callback
| 类型 | 默认值 | 必填 | 说明 | 最低支持版本 |
|---|---|---|---|---|
| function | 无 | 是 | 收到事件的回调函数 | 3.35.0 |
callback 是一个回调函数,接收 object 类型的参数,属性如下:
| 属性名 | 类型 | 说明 | 最低支持版本 |
|---|---|---|---|
| data | string | 接口服务返回的 data | 3.35.0 |
| event | string | 接口服务返回的 event | 3.35.0 |
| lastEventId | string | 接口服务返回的 lastEventId(仅在接口设置了id值时返回) | 3.35.0 |
返回值
无
扫码体验
请使用字节宿主APP扫码
代码示例
<view class="container"> <view class="body"> <view class="page-section"> <view class="ttui-cells"> <view class="ttui-cell"> <view class="ttui-cell__bd">EventSource状态:</view> <view class="ttui-cell__ft"> <text>{{eventSourceStatus}}</text> </view> </view> </view> </view> <view class="btn-area"> <button type="primary" size="40" bindtap="createEventSource" disabled="{{eventSourceStatus === 'open'}}">发起请求</button> <button type="primary" size="40" bindtap="closeEventSource" disabled="{{eventSourceStatus !== 'open'}}">关闭连接</button> <button type="primary" size="40" bindtap="clearData">清除数据</button> </view> <text> 收到的数据:</text> <view class="text-box" scroll-y="true" scroll-top="{{scrollTop}}"> <text>{{text}}</text> </view> </view> </view>
let eventSourceTask; Page({ data: { eventSourceStatus: '', text: '' }, createEventSource() { const eventSourceStatus = this.data.eventSourceStatus; if (eventSourceTask && eventSourceStatus === 'open') return; if (eventSourceTask && eventSourceStatus && eventSourceStatus !== 'open') eventSourceTask.close(); const url = "https://sse-fake.andros.dev/events/"; eventSourceTask = tt.createEventSource({ url }) eventSourceTask.onOpen(() => { console.log('已连接'); this.setData({ eventSourceStatus: 'open' }) }); eventSourceTask.onClose(() => { console.log('eventSource 已断开'); this.setData({ eventSourceStatus: 'close' }) }); eventSourceTask.onError((error) => { console.error('eventSource 发生错误:', error); this.msg('发生错误'); this.setData({ eventSourceStatus: 'error' }); }); eventSourceTask.onMessage((res) => { console.log('eventSource res:', res); const { data, event } = res; if (data && event) { this.setData({ text: this.data.text + `event: ${event}` + '\n' + `data: ${data}` + '\n\n' }); } }); }, closeEventSource() { eventSourceTask.close({ success: res => { console.log('close eventSource success', res); tt.showToast({ title: 'close success', content: JSON.stringify(res), }); this.setData({ eventSourceStatus: 'close' }) }, fail: err => { console.log('close eventSource err', err); } }); }, // 清空数据 clearData() { this.setData({ text: '' }); }, msg(msg) { tt.showToast({ title: msg, icon: 'none' }); }, })
.text-box { margin-bottom: 70rpx; padding: 40rpx; display: flex; min-height: 300rpx; background-color: #FFFFFF; font-size: 30rpx; color: #353535; }
