I have multiple buttons with an attribute called 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. So when the first link is clicked, socket.io would emit "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/
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');
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.