如果這是您唯一的選擇,那麼您可能會錯誤地進行一些操作。無論如何,讓我們看看......只有當兩個事件都發生時。
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