jQuery绑定事件监听器在另一个之前

sen*_*ett 15 jquery

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

麻烦的是,当我

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

事件永远不会被触发,因为prettyPhoto会阻止事件继续(非常正确,否则如果单击超链接,页面将会改变).

prettyPhoto似乎没有提供"开放"回调函数,但如果它确实无法使用它,因为prettyPhoto监听器在布局中的某处设置(我们rel="prettyPhoto"每次都想使用prettyPhoto,并传递params通过URL,这是prettyPhoto推荐的做事方式).我还想将产品详细信息传递给Analytics,排除所有prettyPhoto开幕活动的全球视频开放听众.

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

Jon*_*han 21

理想情况下,你就可以添加你的事件绑定之前,任何人,所以它先执行.

不幸的是,jQuery似乎没有包含任何此类工具.

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

$.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;
};
Run Code Online (Sandbox Code Playgroud)

用法:

$('#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"
Run Code Online (Sandbox Code Playgroud)


Pat*_*ick 15

我正在使用Jonathan的preBind方法,稍加修改,它可以很好地完成这个操作.

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

        $this.bind(type, data, fn);

        var currentBindings = $this.data('events')[type];
        if ($.isArray(currentBindings)) {
            currentBindings.unshift(currentBindings.pop());
        }
    });
    return this;
};
Run Code Online (Sandbox Code Playgroud)

  • 在较新版本的jQuery中,$ this.data('events')[type]`不起作用.你必须使用`$ ._ data(this,'events')[type]` (6认同)

alg*_*thm 6

为我工作的旧jQuery版本和新版本:

/**
 * @link http://stackoverflow.com/a/26892146/655224
 */
jQuery.fn.getEvents = function() {
    if (typeof(jQuery._data) == 'function') {
        return jQuery._data(this.get(0), 'events') || {};
    } else if (typeof(this.data) == 'function') { // jQuery version < 1.7.?
        return this.data('events') || {};
    }
    return {};
};

jQuery.fn.preBind = function(type, data, fn) {
    this.each(function () {
        var $this = jQuery(this);

        $this.bind(type, data, fn);

        var currentBindings = $this.getEvents()[type];
        if (jQuery.isArray(currentBindings)) {
            currentBindings.unshift(currentBindings.pop());
        }
    });
    return this;
};
Run Code Online (Sandbox Code Playgroud)

但请注意,此函数只能返回/预绑定使用jQuery本身设置的事件.

特别感谢@jonathanconway和@Patrick ......


bra*_*aks 5

以下是使用更现代的.On()方法的解决方案的变体.

// Same as .on() but moves the binding to the front of the queue.
$.fn.priorityOn = function (type, selector, data, fn) {
    this.each(function () {
        var $this = $(this);

        var types = type.split(" ");

        for (var t in types) {
            $this.on(types[t], selector, data, fn);

            var currentBindings = $._data(this, 'events')[types[t]];
            if ($.isArray(currentBindings)) {
                currentBindings.unshift(currentBindings.pop());
            }
        }


    });
    return this;
};
Run Code Online (Sandbox Code Playgroud)

用法就像

$(document).priorityOn("click blur change", ".some .selector input", function (e) {
    // Your code.
});
Run Code Online (Sandbox Code Playgroud)