gpt4 book ai didi

javascript - "Existing subscription to channel"而只订阅一次

转载 作者:行者123 更新时间:2023-11-30 08:51:03 25 4
gpt4 key购买 nike

我有一个小片段会抛出“现有 channel 订阅”异常,即使我只调用了订阅方法一次。

这可以通过将订阅请求移到“state_change”处理程序之外来避免,但我想知道这可能是什么原因造成的?也许是 Pusher 库中的错误?

<!doctype html>
<html>
<body>
<h1>Pusher subscribe testcase</h1>
<p>Tip: check your console</p>
<script src="https://d3dy5gmtp8yhk7.cloudfront.net/2.1/pusher.min.js"></script>
<script>
var pusher, channel;
pusher = new Pusher('xxxxxxxxxxxxxxxxx');
pusher.connection.bind('state_change', function(change){
if(change.current === 'connected'){
console.log('connected');
channel = pusher.subscribe('test-channel');
channel.bind('pusher:subscription_succeeded', function() {
console.log('subscribed');
});
}
})
</script>
</body>
</html>

这导致:

connected
subscribed
Pusher : Error : {"type":"WebSocketError","error":{"type":"PusherError","data":{"code":null,"message":"Existing subscription to channel test-channel"}}}

最佳答案

虽然它看起来确实像是库中的错误(请务必报告!),但您无需绑定(bind)到 state_change 事件即可订阅 channel 。

如果您查看 pusher.js 中订阅事件的代码:

prototype.subscribe = function(channel_name) {
var self = this;
var channel = this.channels.add(channel_name, this);

if (this.connection.state === 'connected') {
channel.authorize(this.connection.socket_id, function(err, data) {
if (err) {
channel.handleEvent('pusher:subscription_error', data);
} else {
self.send_event('pusher:subscribe', {
channel: channel_name,
auth: data.auth,
channel_data: data.channel_data
});
}
});
}
return channel;
};

您会看到它首先会通过 channels.add 方法将您的 channel 添加到内部 channel 列表中,如下所示:

prototype.add = function(name, pusher) {
if (!this.channels[name]) {
this.channels[name] = createChannel(name, pusher);
}
return this.channels[name];
};

它只会在您之前没有订阅的情况下添加 channel 。

因此,如果您要在连接建立之前订阅一个 channel ,Pusher 客户端只会将该 channel 添加到列表中。客户端建立连接后,它将通过 subscribeAll 方法为其列表中的每个 channel 再次调用 subscribe 方法:

this.connection.bind('connected', function() {
self.subscribeAll();
});

看到此时this.connection.state 已连接,它将连接。

所以,回顾一下,不要费心绑定(bind)到 state_change 事件来订阅,只需订阅,就像这样:

<!doctype html>
<html>
<body>
<h1>Pusher subscribe testcase</h1>
<p>Tip: check your console</p>
<script src="https://d3dy5gmtp8yhk7.cloudfront.net/2.1/pusher.js"></script>
<script>
var pusher, channel;

pusher = new Pusher('XXXXXXXXXXXXXXXX');
channel = pusher.subscribe('test-channel');
channel.bind('pusher:subscription_succeeded', function() {
console.log('subscribed');
});
</script>
</body>
</html>

关于javascript - "Existing subscription to channel"而只订阅一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17833502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com