2012-09-30 39 views
0

我在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; 
    } 
}); 
+0

你为什么不只是当它改变时禁用