jQuery plugin with trigger in click event

0

jQuery plugin:

(function($){

    $.fn.extend({
        meuPlugin: function(){
            $('body').on('click', this, function( e ){
                console.log( $(this).attr('href') );
                return false;
            });
        }
    });

})(jQuery);

HTML selector:

<a href="um_link_qualquer.php" id="link_teste">Meu link</a>

Plugin Call:

$(document).ready(function(){
    $('#link_teste').meuPlugin();
});

Problem:

$(this).attr('href') is referring to body , not $('#link_teste') in the plugin call.

• My first attempt was to change:

$('body').on('click', this, function( e ){ to this.on('click', function() {

(function($){

    $.fn.extend({
        meuPlugin: function(){
            //$('body').on('click', this, function( e ){
            this.on('click', function() {
                console.log( $(this).attr('href') );
                return false;
            });
        }
    });

})(jQuery);

PS: It worked, but not 100%. It turns out that if I assign the plugin to an element that will be loaded later via ajax, the click will not call the plugin.

• I also tried with e.target , the only difference is that instead of returning body , returns the clicked element , whatever.

• This is another attempt:

// plugin
$.fn.extend({
    meuPlugin: function () {
        console.log( this.attr('href') );
        return false;
    }
});
// chamada do plugin no elemento #link_teste
$(document).ready(function(){
    $('body').on('click', '#link_teste', function ( e ) {
        e.preventDefault();
        $(e.target).meuPlugin();
    });
});

It works exactly as it should, but the plugin's call has become very "dirty." I need something more precise and clean as already mentioned:

$('#link_teste').meuPlugin();

Objective:

I need the attributes of #link_teste referencing it inside the plugin, such as href , action , method , and that is compatible with ajax calls: / p>

$('#link_teste').meuPlugin();

Thank you in advance!

    
asked by anonymous 12.02.2018 / 00:14

1 answer

1

Remember that in Event Delegation you should keep the hierarchy of elements. The parent element, delegates the function to its descendants that match the selector.

In this case, <body> is delegating to <a> elements that have the corresponding ID.

Ex:

$.fn.extend({
  meuPlugin: function () {
    let id = '#' + $(this).attr('id');
    
    $('body').on('click', id, function () {
      console.log($(this).attr('href'));
    });
  }
});

$(function () {
  $('#link_teste').meuPlugin();
  $('#outro_link').meuPlugin();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ahref="http://www.google.com" id="link_teste">Link qualquer</a>
<br><br>
<a href="http://www.youtube.com" id="outro_link">Outro link qualquer</a>
<br><br>
<button type="button">Clique aqui para testar se irá ativar</button>

(Click "run" and check the output of console )

    
12.02.2018 / 00:50