简体   繁体   中英

Javascript listen two events and fire one function

如何检测两个不同的事件,并且只有在检测到所有两个事件时才会触发一个函数?

This functions are created:

    var got = { first : 0, second : 0 };
    function fire(event_type)
    {
      got[ event_type ] = 1;
      if( got.first && got.second )
      {
        //do stuff and reset
         got = { first : 0, second : 0 };
      }
    }

This is the listener part:

    document.onclick=function (){fire('first');}
    document.onmouseover=function (){fire('second');}

This is where Promises excel:

var prom1 = new Promise(function(resolve, reject){
    $("foo").one("someEvent", resolve);
});
var prom2 = new Promise(function(resolve, reject){
    $("bar").one("otherEvent", resolve);
});
Promise.all([prom1, prom2]).then(function(){
    //woo!
});

Detect them both, record when you've received one, and check to see if the other has already been received (which means BOTH have been received). Remember to "forget" about them when this happens.

You have many options.

For example: (without using any library)

(function(){
a=false; b=false;
function doIt(){
alert('both function have fired')
}
document.onclick=function (){a=true;if(a&&b) doIt()}
document.onmouseout=function (){b=true;if(a&&b) doIt()}

})()

JsFiddle: http://jsfiddle.net/3nDds/ You need to click inside the document, and move out the document.

Another option would be to use the data attribute.

http://jsfiddle.net/vpA3A/3/

$("#mybutton").on("mouseover", function(event) {
    var $button = $(this);
    $button.data("mouse", true);
    dowork($button);
}).on("click", function(event) {
    var $button = $(this);
    $button.data("click", true);
    dowork($button);
});

function dowork($button)
{
    if($button.data("mouse") == true && $button.data("click") == true) {
        alert('both events');
        $button.data('mouse', false).data('click', false);
    }
}

如果是两个状态,则在第一个事件侦听器之后将函数调用放在彼此内部。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM