I have an ajax call that should be executed when and only when the certain flag is set somewhere else in the code.
I cannot make this call directly in the function that sets the flag because I do not need to make this call each time when flag is set.
It is a bit hard to explain so the best illustration I can think of is something like:
The wolf can eat the Red Hat when and only when she is in her grandma’s house.
However not every time she comes to this house, there is a wolf to eat her. From the other side each time when she is here and the wolf is here, the wolf will eat her.
I wonder, can I use $.when(theFlag) for this purpose?
var theRedHatIsHere = false;
function waitForRedHat()
{
.....
theRedHatIsHere = true;
}
function wolfIsHungry(link)
{
$.when(theRedHatIsHere)
{
$.ajax({
type: "POST",
url: "php/eatredhat.php?",
data: ddd,
async: false,
success: function(msg){
console.log( "Eaten" );
window.location.href = link;
}
});
}
}
Use custom events or Publish/Subscribe pattern instead of bending $.when to do something that is not supposed to do. It is a well known pattern, it helps decouple your components and you have the flexibility for example to have multiple subscribers to the event, stop listening to the event at some point or reacting to it only once.
Subscribe to a custom event with jQuery.on
whenever the wolf gets hungry, instead of setting that boolean value just raise that custom event: