jQuery绑定事件侦听器 [英] jQuery bind event listener before another

查看:233
本文介绍了jQuery绑定事件侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 prettyPhoto 插件打开模态样式的内容容器,并尝试与Google Analytics(分析)的事件跟踪"集成以跟踪视频何时打开.

Using the prettyPhoto plugin to open modal-style content containers, and trying to integrate with Google Analytics' Event Tracking to track when videos get opened.

麻烦是,当我

$('a.videoClickListener').click(function(event){
    console.log('here');
    _gaq.push(['_trackEvent', 'Product Page', 'Video Open', '<?php echo $product->getNameWithManufacturer(); ?>']);
});

该事件永远不会触发,因为prettyPhoto会阻止该事件继续进行(很正确,否则,如果单击超链接,则页面将发生更改).

the event is never fired, as prettyPhoto stops the event from continuing (quite rightly, as otherwise the page would change if a hyperlink was clicked).

prettyPhoto似乎没有提供打开"回调函数,但如果这样做,我还是无法使用它,因为prettyPhoto侦听器设置在布局中的某个位置(每次我们想使用rel="prettyPhoto"使用prettyPhoto,然后通过URL传递参数,这是prettyPhoto推荐的处理方式).我还想将产品详细信息传递给Google Analytics(分析),从而在所有prettyPhoto开幕式活动中排除一个全局的视频开幕式监听器.

prettyPhoto does not seem to provide an 'open' callback function, but if it did I couldn't use it anyway, as the prettyPhoto listeners are set up somewhere in the layout (we use rel="prettyPhoto" every time we want to use prettyPhoto, and pass params through the URL, which is the prettyPhoto-recommended way of doing things). I would also like to pass the product details to Analytics, ruling out a global video-opening listener across all prettyPhoto opening events.

如何在prettyPhoto侦听器之前 绑定我的侦听器?如果事实证明我必须使用.unbind(),然后绑定我的侦听器,然后重新绑定prettyPhoto,我如何才能取消绑定插件中指定的处理程序?

How can I bind my listener before the prettyPhoto listener? If it turns out I have to use .unbind(), then bind my listener, and then rebind prettyPhoto, how can I unbind a handler specified in a plugin?

推荐答案

理想情况下,您可以在之前添加您的事件绑定,以便其执行首先.

Ideally, you would be able to add your event binding before any others, so that it executes first.

不幸的是,jQuery似乎没有任何此类功能.

Unfortunately, jQuery doesn't seem to include any such facility.

但是,我已经编写了 preBind方法,它似乎可以解决问题:

However, I've coded a preBind method, which seems to do the trick:

$.fn.preBind = function(type, data, fn) {
  this.bind(type, data, fn);

  var currentBindings = this.data('events')[type];
  var currentBindingsLastIndex = currentBindings.length - 1;

  var newBindings = [];

  newBindings.push(currentBindings[currentBindingsLastIndex]);

  $.each(currentBindings, function (index) {
    if (index < currentBindingsLastIndex)
      newBindings.push(this);
  });

  this.data('events')[type] = newBindings;

  return this;
};

用法:

$('#button').bind('click', function() {
  console.log('world');
});

// 2nd apostrophe for the selector was missing
$('#button').preBind('click', function() {
  console.log('hello');
});

$('#button').click();

// Output:
//
// > "hello"
// > "world"

这篇关于jQuery绑定事件侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆