Reputation: 11
I want to do a callback after a eventlistner has completed. My listner looks about this way:
aktivList.addEventListener("click", function (ev) {
$("#printMenu").show();
$("#imageForm").hide();
$(".polaroid").hide();
$("#searchId").hide();
switch (activeFolderGroupeIs) {
case "butikkOppgaver":
firbListnerButikk(firebaseAktivListFolder, ev);
break;
case "oppgavelisteAnsatte":
firbListnerBS(firebaseAktivListFolder, ev);
break;
case "varebytteOppgaver":
firbListnerVarebytte(firebaseAktivListFolder, ev);
break;
default:
};
if (deleteListMode) {
deleteMode = true;
//$("#inputFields").slideUp();
firebaseRefRemove(currentList, firebasePassivListFolder);
firebaseRefNumberOfChild();
};
});
When all this code is completed, i want to run another function. (all this functions works as is, but if I add another function at the end, it runs before everything else is finished).
My event listner puts data in textfield. When event lister is completed, i want to run another function. I tried to search for callback and promises, but no one talked about adding it to this code.. any idea?
Regards Jan
Upvotes: 1
Views: 36
Reputation: 31024
You can dispatch a custom event to notify when the async operation finished:
With pure javascript:
var btn = document.getElementById('btn');
var txt = document.getElementById('txt');
var myevent = new Event('myEvent');
btn.addEventListener('myEvent', function (e) {console.log('finished the job!')});
btn.addEventListener("click", function (ev) {
setTimeout(function(){
// async operation here...
txt.value = 'hi there';
btn.dispatchEvent(myevent);
},1000);
});
<button id="btn">Click Me</button>
<input id="txt" type="text" />
With jQuery:
var btn = $('#btn');
var txtEl = $('#txt');
btn.on("click", function(ev) {
setTimeout(function() {
// async operation here...
txtEl.val('hi there');
btn.trigger('myEvent');
}, 1000);
});
btn.on('myEvent', function(e) {
console.log('finished the job!')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">Click Me</button>
<input id="txt" type="text" />
Upvotes: 1