如果这是您唯一的选择,那么您可能会错误地进行一些操作。无论如何,让我们看看......只有当两个事件都发生时。
var HandleTwoEvents = function (key1, key2) {
this.count = 0;
this.pack = [];
$self = this;
this.startListening = function(fn) {
fn = fn || function() {}
window.addEventListener(key1, function (ev) {
if ($self.pack.indexOf(key1) < 0) {
$self.pack.push(key1);
$self.count++;
if ($self.count == 2) {
fn();
$self.count = 0;
}
}
console.log(key1, ev);
});
window.addEventListener(key2, function (ev) {
if ($self.pack.indexOf(key2) < 0) {
$self.pack.push(key2);
$self.count++;
if ($self.count == 2) {
fn();
$self.count = 0;
}
}
console.log(key2, ev);
});
}
}
原谅我,我总是用这个函数来创建事件
function createEvent(name, obj) {
var evt = document.createEvent("Event");
evt.initEvent(name, true, true);
evt.data = obj;
dispatchEvent(evt);
}
现在,同时记录事件......
var both = new HandleTwoEvents("EventKeyOne", "EventKeyTwo");
both.startListening(function() {console.log("This means that both Events have taken place")});
现在,让我们来测试...
createEvent("EventKeyOne", {});
//key, data are the arguments ... function defined in startListening above does not execute, and upon inspection, both.count is seen to be 1
createEvent("EventKeyTwo", {});
//Now, function executes.
//It also works if "EventKeyTwo" is raised before "EventKeyOne"
快乐编码! PS:我敢肯定,有更好的方法来处理$ self变量的使用,并带有一些函数绑定。我从来没有学过它。
@clijsters你有更多的意见吗? – Hbaecklund
我认为@Ikechi迈克尔的输入是相当你所需要的。 – Clijsters