chrome javascript事件处理问题

时间:2011-04-10 11:32:34

标签: javascript google-chrome google-chrome-extension

我有这个问题,在谷歌浏览器中同时调用多个事件处理程序。 如果是书签创建事件,以下代码将触发eventHandler函数。

chrome.bookmarks.onCreated.addListener(eventHandler);

创建多个书签时,例如将几个书签栏链接从firefox拖动到chrome,会同时运行多个 eventHandler 函数,从而导致不良影响。我需要确保一次只运行一个 eventHandler 实例,并以先到先得的方式处理事件。有没有办法在javascript中确保这一点?

2 个答案:

答案 0 :(得分:2)

正如Jakub所说,异步事件处理是JavaScript的一个不错的选择。我建议重新考虑你的应用程序流程来支持它,而不是试图序列化它。此外,您不会承诺事件触发的顺序是您期望触发的顺序。拖动多个书签可以按任意顺序生成事件。

如果你真的需要确保程序按照它们的顺序处理事物,并且一次只处理一个项目,你可以将逻辑分成两部分:eventHandler本身可以是一个函数填充您需要以某种方式处理的事件队列,并且您可以使用另一个在超时驱动的循环中运行的函数,检查队列,关闭项目并处理它。类似于以下(未经测试的)代码:

function SerializedEventHandler() {
  chrome.bookmarks.onCreated.addListener(this.enqueue.bind(this));
}

SerializedEventHandler.prototype = {
  queue_: [],

  timer_: null,

  enqueue: function (e) {
    this.queue_.push(e);
    this.startProcessing();
  },

  startProcessing: function () {
    if (!this.timer_)
      this.timer_ = setTimeout(this.process.bind(this), 100);
  },

  process: function () {
    if (this.queue_.length) {
      var item = this.queue_.shift();
      // do something with `item`
      this.timer_ = clearTimeout(this.timer_);
      this.startProcessing();
    }
  }
};

这有意义吗?

答案 1 :(得分:0)

我认为没有一种非常优雅的方式来做到这一点。 JavaScript的全部意义在于它是基于事件的。

一种破解它的方法可能是使用setTimeout并且暂停时间很短。

var timeout;

chrome.bookmarks.onCreated.addListener(function(ev) {
  clearTimeout(timeout);
  timeout = setTimeout(function() {eventHandler(ev);}, 5);
});