[英]socket.io: Emit button's attribute value on click?
I have multiple buttons with an attribute called groupName
. 我有多个带有名为
groupName
的属性的按钮。 They look like this: 他们看起来像这样:
<a href="#" class="fireGroup btn btn-info btn-lg" groupName="SCENE_I">SCENE I</a>
<a href="#" class="fireGroup btn btn-info btn-lg" groupName="SCENE_II">SCENE II</a>
<a href="#" class="fireGroup btn btn-info btn-lg" groupName="SCENE_III">SCENE III</a>
I'm trying to figure out how to get socket.io to emit the link's groupName value when clicked. 我试图弄清楚如何使socket.io在单击时发出链接的groupName值。 So when the first link is clicked, socket.io would emit "groupName - SCENE_I"
因此,当单击第一个链接时,socket.io将发出“ groupName-SCENE_I”
How could this be accomplished? 如何做到这一点?
It seems you want something similar to a chat -- where a click on a link acts as a user sending a message to the server, and the server would emit that to a room (to other users, I suppose?) 似乎您想要一个类似于聊天的东西-单击链接就像用户向服务器发送消息一样,服务器会将其发送到房间(我想是向其他用户发送的)?
If that's the case, you should take a look at this example: http://socket.io/get-started/chat/ 如果是这样,您应该看一下以下示例: http : //socket.io/get-started/chat/
You would do something like this on the client side: 您将在客户端执行以下操作:
<html>
<head>
</head>
<body>
<a href="#" class="fireGroup btn btn-info btn-lg" groupName="SCENE_I">SCENE I</a>
<a href="#" class="fireGroup btn btn-info btn-lg" groupName="SCENE_II">SCENE II</a>
<a href="#" class="fireGroup btn btn-info btn-lg" groupName="SCENE_III">SCENE III</a>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
$(document).ready(function(){
var socket = io();
// listen to server events related to messages coming from other users. Call this event "newClick"
socket.on('newClick', function(msg){
console.log("got new click: " + msg);
});
// when clicked, do some action
$('.fireGroup').on('click', function(){
var linkClicked = 'groupName - ' + $(this).attr('groupName');
console.log(linkClicked);
// emit from client to server
socket.emit('linkClicked', linkClicked);
return false;
});
});
</script>
</body>
</html>
On the server side, still taking the chat idea into consideration: 在服务器端,仍然考虑聊天想法:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('./index.html');
});
io.on('connection', function(socket){
// when linkClicked received from client...
socket.on('linkClicked', function(msg){
console.log("msg: " + msg);
// broadcast to all other users -- originating client does not receive this message.
// to see it, open another browser window
socket.broadcast.emit('newClick', 'Someone clicked ' + msg) // attention: this is a general broadcas -- check how to emit to a room
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.