觸發器功能似乎是同步的。也就是說,所有綁定函數似乎都是同步執行的(被調用的函數可能會異步執行某些操作,但這不是問題)。jQuery觸發器功能是否保證同步
對於自定義和非自定義(點擊,懸停等)事件,這是否正確?是否有任何JavaScript單線程保證不成立的事件?
如果它是真的,那麼可以改變行爲來異步執行它們,而不在每個綁定函數中插入超時值?
這裏是這表明該問題的示例:
var ele = $('#blah');
// Example of the bound function doing something synchronously
ele.bind('customEvent.sync', function() {
// Do something synchronously
window.foo = 'foo';
});
// Example of the bound function doing something asynchronously
ele.bind('customEvent.async', function() {
window.setTimeout(function() {
// Do something asynchronously
window.bar = 'bar';
}, 0);
});
// Trigger both events
ele.trigger('customEvent');
// If trigger is guaranteed to be synchronous this should alert 'foo:undefined' or possibly 'foo:bar' depending on whether the asych function was called first
// If trigger is NOT synchronous 'undefined:undefined', 'foo:undefined', 'undefined:bar', or 'foo:bar' could be alerted
alert(window.foo + ':' + window.bar);
UPDATE 參見:Is JavaScript guaranteed to be single-threaded? 自定義事件都保證由於JavaScript的的單線程性質是同步的。由於瀏覽器不一致,某些內置事件類型可能不同步。
如果你給出了你關心的問題的例子,可以更容易地遵循 – charlietfl
我的擔心是我是否可以依賴被稱爲我的觸發器的綁定函數在觸發 – Kyle
之後的行之前執行問題似乎是衝突:「被調用的函數可能做一些異步......但這不是問題」和「可以改變執行異步的行爲,而不會將超時插入到每個綁定函數中」(我認爲這不是問題?) – 2012-12-24 04:29:23