Ably实时通道Channel.off与Channel.unsubscribe方法的区别
Ably JavaScript SDK Channel.off 方法功能及与unsubscribe的区别
Channel.off 核心功能
Channel.off 用于移除通道生命周期事件的绑定监听器。你通过Channel.on方法绑定的通道状态类事件,都需要通过off方法解除绑定,支持三种调用形式:
- 无参调用
channel.off():移除当前通道绑定的所有生命周期事件监听器 - 仅传事件名调用
channel.off('attached'):移除指定事件下绑定的所有监听器,可监听的生命周期事件包括attached、detached、suspended、failed、update等 - 传事件名+对应回调调用
channel.off('attached', yourHandler):仅移除该事件下绑定的指定回调监听器
与Channel.unsubscribe的核心差异
二者的作用域完全不同:
Channel.unsubscribe针对的是通道内的业务消息订阅逻辑,仅用来移除你通过Channel.subscribe绑定的、用于接收通道推送的业务消息的监听器,和通道本身的生命周期事件无关- 和
off类似,unsubscribe也支持无参移除所有消息监听器、仅传消息名移除对应消息的所有监听器、传消息名+回调移除指定监听器三种调用方式
用法示例
const channel = ably.channels.get('test-channel') // 绑定通道生命周期事件,后续用off移除 const handleAttached = () => console.log('通道完成附着,可正常收发消息') channel.on('attached', handleAttached) // 绑定业务消息监听,后续用unsubscribe移除 const handleOrderMsg = (msg) => console.log('收到订单更新', msg.data) channel.subscribe('order_update', handleOrderMsg) // 解绑生命周期事件 channel.off('attached', handleAttached) // 解绑业务消息监听 channel.unsubscribe('order_update', handleOrderMsg)
内容的提问来源于stack exchange,提问作者camtastic
相关产品推荐
相关产品推荐

