Skip to content

Instantly share code, notes, and snippets.

@misterussell
Last active October 26, 2016 13:59
Show Gist options
  • Save misterussell/297443f7748c79d138cec02f317b468b to your computer and use it in GitHub Desktop.
Save misterussell/297443f7748c79d138cec02f317b468b to your computer and use it in GitHub Desktop.
Example of a user specific delete button.
var settings = {
url: '<<server link here>',
type: 'GET',
success: (data, status, xhr) => {
//THE forEach loop below runs through our server, pulling all current data to display.
data.forEach( (message, i, arr) => {
let messageLine = $(`
<li class=>
<span class="postDetails">${message.userName} (${moment(message.timeStamp).format('DD/MM/YY, h:mm a')}):</span>
<span class="postBody">${message.body}</span>
</li>`);
//HERE we add the messages to our list, one at a time.
$('.messages').prepend(messageLine);
//SESSION was previously defined upon login. By matching a user can only delete their messages.
if(message.userName === session.userName) {
console.log(session.userName);
messageLine.append(`
<button class="delete ${message._id}">
Delete
</button>`);
}
//BY searching for a ID specific class we are able to apply the click handler to only specific objects,
//rather than all buttons that are created. This is important when dealing with single objects.
$('.' + message._id).on('click', (e) => {
//TARGET is defined as a new object, from a constructor module that created the original messages.
let target = new Message(message.userName, message.body, message.timeStamp, message._id);
console.log(target);
//.delete() triggers an ajax DELETE query that takes the objects ID to process the delete.
target.delete();
});
});
},
error: () => {
console.log('Chat log request:FAIL');
}
};
$.ajax(settings);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment