Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Waiting for Multiple Events to fire

Is it possible to "wait" for multiple events before executing a function? I know its possible with jQuery deferred obejcts to use $.when to wait for two promises to resolve but I wondered if its possible with just plain old events?

Lets say a click event and a custom event trigger an alert, for example:

$.when("click", "customEvent").then(function(){ alert("yay"); });
like image 837
Jon Wells Avatar asked Feb 15 '13 10:02

Jon Wells


1 Answers

You could use deferred, you just have to create them yourself.

var clickDfd = $.Deferred();
var eventDfd = $.Deferred();
$("div").on("click", function(e) {
   clickDfd.resolve();
});

$("div").on("some-event", function(e) {
   eventDfd.resolve();
});

$.when(clickDfd, eventDfd).done(function(){ 
    alert("yay"); 
});
like image 84
Paul Hoenecke Avatar answered Oct 16 '22 11:10

Paul Hoenecke