I am using mongodb with mongoose to maintain a list of stocks across clients. I want to simultaneously update the list using socket.io when one user makes a change. I can connect to the socket and update client javascript but not make changes to variable on server side.
app.js - Server
// connect to socket.io
io.on('connection', function (socket) {
console.log('Client Connected..');
///retrieve new stock from client
socket.on('submitStock', function (data) {
console.log(data);
///do mongodb stuff here
///send new stocks to all clients
socket.emit('activeStocks', data);
});
});
script.js - client
var socket = io.connect();
///connect to socket
socket.on('connect', function (data) {
socket.emit('join', 'Hello World from client');
});
///use submit button to send the new stock to server
$('#addStock').on('submit', function(e){
//var stockList = $('#stockList');
socket.emit('submitStock', 'here is the data');
});
//retrieve the new stock from the server and update list
socket.on('activeStocks', function(data) {
//how to update activeStocks here??
console.log(data);
});
index.ejs
<% if (message.length > 0) { %>
<div class="alert alert-danger"><p><%= message %></p></div>
<% } %>
<div class="container">
<form id="addStock" action="/add" method="post">
<div class="form-inline">
<input type="text" class="form-control" name="stockTicker" placeholder="Enter a stock ticker">
<button type="submit" class="btn btn-primary"><span>Add Stock</span></button>
</div>
</form>
</div>
<% if (activeStocks) { %>
<% for (var i=0; i< activeStocks.length; i++) { %>
<div> <%- activeStocks[i] %></div>
<% } %>
<% } %>