【问题标题】:jQuery Live implementation in Prototype原型中的 jQuery Live 实现
【发布时间】:2011-01-24 01:39:46
【问题描述】:
Element.implement({
    addLiveEvent: function(event, selector, fn){
        this.addEvent(event, function(e){
            var t = $(e.target);

            if (!t.match(selector)) return false;
                fn.apply(t, [e]);
        }.bindWithEvent(this, selector, fn));
    }
});

$(document.body).addLiveEvent('click', 'a', function(e){ alert('This is a live event'); });

上面的代码是在similar question 中完成的,用于在 Mootools 中实现 .live 行为。我读过这个问题:Prototype equivalent for jQuery live function

如何在 Prototype 中实现这一点?大概可以这样实现:

document.liveobserve('click', 'a', function(e){ alert('This is a live event');

已编辑以明确问题。

【问题讨论】:

  • 老实说,在 mootools 中(尽管这在当前版本中是不稳定的),它现在可以原生/不同地工作,例如:$('foo').addEvent('click:relay(li)'); - 不确定这是否有助于原型。
  • @Dimitar。很高兴知道 +1

标签: prototypejs mootools jquery


【解决方案1】:

最简单(也许不是最快或最好)的方法看起来像这样:

Element.live = function(evType, evSelector, evBlock) {
  var mySelector = evSelector;
  var myBlock = evBlock;
  this.observe(evType, function(ev) {
    if (ev.target.match(mySelector)) {
      evBlock(ev);
    }
  });
};

参数 evSelector 和 evBlock 分配给局部变量,因此它们可用于事件处理程序(它是一个闭包)。传递的块 evBlock 像普通的 Prototype 事件处理程序一样被传递事件对象。

应该注意,这将处理“evType”类型的每个事件,因此如果它是 mouseMove/mouseOver,这将使您的页面变慢。由于 FireBug 必须单步执行的事件数量,因此 FireBug 可能只会在你身上睡觉。

编辑:根据 cmets 更改

【讨论】:

  • 我相信这段代码不需要触发事件的元素是调用 .live 的元素的后代,这是 jQuery 所做的。您只检查事件目标是否匹配evSelector,还应该检查它是否是self 的后代(在外部函数中设置为this,因为观察调用将不再具有相同的绑定对象)。
  • 好点,但是对这个而不是文档执行观察应该可以解决这个问题,不是吗?
猜你喜欢
  • 2010-12-01
  • 1970-01-01
  • 2019-09-21
  • 1970-01-01
  • 2012-01-07
  • 1970-01-01
  • 1970-01-01
  • 2016-04-23
  • 1970-01-01
相关资源
最近更新 更多