简体   繁体   English

如何在点击事件中启动socket-io?

[英]How can I launch socket-io on a click event?

I want to make it so when I click an element with class chatroom, socketio will connect to flask. 我要这样做,所以当我单击带有类chatroom的元素时,socketio将连接到flask。 Here is the server side: 这是服务器端:

@socketio.on('joined')
def handle_connections(data):
    username = session['Username']
    socketio.emit('status', {'msg': username + ' has entered the room.' });

Here is the javascript 这是JavaScript

var socket = io.connect( 'http://' + document.domain + ':' + location.port );
$(document).ready(function(){
    $('.chatRoom').click(function(event){   
            event.preventDefault();

            socket.on( 'connect', function() {
                socket.emit( 'joined', {});
            }); 
    });

    socket.on( 'status', function(data){
            console.log("user connected");
    });
});

Without the jquery selector, the chatroom works. 如果没有jquery选择器,则聊天室将起作用。 How can I make it work with the selector? 如何使其与选择器一起使用?

You can send ajax call request for connect and handle that in socket. 您可以发送ajax呼叫请求以进行连接并在套接字中处理该请求。 In think below code snippet can help you other way round. 在下面的代码中,代码片段可以为您提供其他帮助。

`$(document).on('click', function(event){
    socket.emit('myClick', {id: event.target}); 
 }
 var socket = io.connect('http://localhost'); 
    socket.on('myClick', function (data) { 
    $(data.id).trigger('click'); 
 } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM