我在select
元素的change
事件上有一個偵聽器:在發生變化時,讀取文件並計算複雜的SVG並將其加載到DOM(讀取:需要一定數量的CPU週期)。問題在於,如果您非常快速地更改select
(通過編碼鍵盤快捷鍵),則會將多件事物加載到SVG容器中 - 我只希望每次加載一個。爲了嘗試解決這個問題,我已經做到了這一點(半準):異步JS問題 - 變量範圍或其他錯誤?
select.on("change", function() { queue(this.val); });
var queuedFile, state = "ready";
function queue(file) {
queuedFile = file;
// NB: in real code, queuedFile is a property and the getter empties the queue
if (state === "ready") { loadFile(queuedFile); }
}
function loadFile(file) {
state = "busy";
ajaxGet(file, function(result) {
// lots of statements, iterators, calls to other fns
state = "ready";
// NB: again in real code the getter empties the queue
var qf = queuedFile;
if (qf) { clearSVG(); loadFile(qf); }
}); // end ajaxGet
}
也就是說:在select
變化,排隊的新文件,如果文件加載不旺加載另一個文件,加載它,否則什麼都不做。當文件加載器完成時,如果有一個排隊的文件,清除SVG並加載排隊的文件。看起來像這樣應該只允許一次在SVG容器中的一個文件。
實際上,state
絕不是"busy"
當它在queue()
中檢查時,所以我仍然將多個文件加載到SVG中。 A console.log(state)
之後state = "busy"
顯示"busy"
雖然。我在這裏錯過了什麼?我不認爲這是queuedFile
範圍的問題。
爲了完整起見,我的隊列屬性是這樣的:
// given: all of this code is enclosed in a function that returns an object "viewer".
// (only one instance of the "viewer" is created)
Object.defineProperty(viewer, "queuedFile", {
get: function() {
console.log("dequeuing", this.filequeue);
var buffer = this.filequeue;
this.filequeue = null;
return buffer;
},
set: function (newval) {
console.log("queuing", newval);
this.filequeue = newval;
}
});
你爲什麼不只是當它改變時禁用
@ianpgall可以工作,但會對UI造成破壞性影響。 – ZachB
它怎麼樣使它毀滅?爲什麼排隊select元素的變化,可能會創建數十個SVG操作來綁定瀏覽器。完成後您仍然可以恢復焦點。你也可以使用顯示「加載」的模式來「禁用」整個頁面。 – Ian