Reputation: 684
I have a chat app I am making and right now, when you open the app the page runs an SQL query and pulls the last 25 messages with an isactive = 1
check. When a user posts a message, I am using Socket.io and Node.js to echo the message to the other users and append it to the chat screen. It's also submitted to the database at the same time so new users will see the message. This is the code I am using to append the messages right now (will style later)
socket.on( 'message', function( data ) {
console.log("saw a request to the socket");
var actualContent = $( "#messages" ).html();
var newMsgContent = '<li> NAME: ' + data.name + ' = ID: ' + data.id + ' = AVATAR: ' + data.avatar + ' = MESSAGE: ' + data.message + '</li>';
var content = newMsgContent + actualContent;
$( "#messages" ).html( content );
});
Since I am just appending the message, it doesn't have a function to remove messages without reloading, and it also will continue to post to your screen forever as chat messages are posted, which will lead to MASSIVE scroll windows and usage on the page.
Is there a way to limit this to show only the 25 most recent messages? Or should I, instead of having the system append the messages, just reload the content div with the most recent data from the database? The downside I see to this is it will create a LOT more database calls and clog up the SQL servers. Whats a better way to communicate these events?
I am new to Socket and Node, and I love it so far. My previous chat engine used pure JS and did a check ever 4 seconds for content and if there was a change then it would reload the whole div. This left a delay in messages and was really clunky feeling so I like the speed on Node support. Thanks in advance!
Upvotes: 0
Views: 531
Reputation: 13014
Use slice
when inserting back the elements:
socket.on( 'message', function( data ) {
console.log("saw a request to the socket");
var actualContent = $( "#messages" ).html();
var newMsgContent = '<li> NAME: ' + data.name + ' = ID: ' + data.id + ' = AVATAR: ' + data.avatar + ' = MESSAGE: ' + data.message + '</li>';
var content = newMsgContent + actualContent;
content = $(content).slice(0, 25).map(function(i, x) { return x.outerHTML }).toArray().join(''); // Will return first 25 messages
$( "#messages" ).html( content );
});
Upvotes: 1