The problem
I have an (AWS serverless) chat application which has a send button. When clicked, it POSTS
a message to a DynamoDB table. I've debugged the backend of things, and it seems like the bug is coming from my javascript. I've posted relevant code below.
My chat.html
file containing the send button:
...
<input type="text" class="form-control" id="message"/>
<span class="input-group-btn">
<button type="button" class="btn btn-primary" id="send">Send</button>
</span>
...
<script src="static/script.js"></script>
<script type="text/javascript">
$(function() {
$("#send").off().on('click', window.Chat.send);
});
</script>
My 'script.js' file containing the Chat.send()
:
Chat.send = function(){
$.post(endpoint + location.hash.substring(1), {message: $('#message').val()}).done(function(){
$('#message').val('').focus();
Chat.load();
})
};
Chat.load = function(){
// periodically makes a GET request to load new messages dynamically
// a little lengthy and not sure relevant but will edit this with the code if someone needs it
}
Edit after following @@MauricioCárdenas's comment
My chat.html
file's script was revised to:
<script type="text/javascript">
$(function() {
document.removeEventListener('click', window.Chat.send);
$("#send").off().on('click', window.Chat.send);
});
</script>
Issue still persists.
Edit after following @Teemu's comment
When I right click on #send
button and inspect then head to "Event Listeners" tab, under click
I get the following:
click
>document [Remove] bootstrap.min.js:6
>document [Remove] bootstrap.min.js:6
>document [Remove] bootstrap.min.js:6
>document [Remove] bootstrap.min.js:6
>document [Remove] bootstrap.min.js:6
>document [Remove] bootstrap.min.js:6
>document [Remove] bootstrap.min.js:6
>document [Remove] bootstrap.min.js:6
>document [Remove] bootstrap.min.js:6
>button#send.btn.btn-primary [Remove] script.js:78
Perhaps bootstrap is attaching multiple click events to my button? What's confusing is that, why is it only sending my message twice and not 10 times, given the number of attached event listener above? I tried removing the 9 event listeners from bootstrap
but still no dice.
What I have tried thus far
Per similar SO posts from the past, I have tried using e.stopImmediatePropagation()
(post):
$('#send').off().on('click', function(e){
e.stopImmediatePropagation();
window.Chat.send();
})
I've tried returning false (post):
$('#send').off().on('click', function(){
window.Chat.send();
return false;
})
I've tried debugging the click event using $._data($('#send')[0], "events")
in the console and viewing the handler function - of which there's only one(post):
// this returns an array with one element and points to the correct handler function
{click: Array(1)}
...
...
// the handler function is below
Chat.send = function() {
//...see above for the definition
}