jQuery bind event listener before another

后端 未结 6 1033
無奈伤痛
無奈伤痛 2020-12-13 21:00

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.

6条回答
  •  自闭症患者
    2020-12-13 21:58

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

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

    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;
    };
    

    Usage:

    $('#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"
    

提交回复
热议问题