How to use my jQuery extension in the on function?

2

In jQuery, I know you can extend and create functions for certain types of operations through $.fn .

So:

(function ( $ ) {

    $.fn.clickOut = function (callback) {

        var that = this;

        $(document).click(function (e) {

            if ( $(e.target).closest(that).size() > 0) {

                return;
            }

            $.isFunction(callback) && $.proxy(callback, that)(e);
        });
    }

})( jQuery )

The function works correctly. But how can I make it work with on , because I need to assign it to dynamically created elements.

Is there any way to "create a function" (I do not know how else to say this) to on of jQuery ?

Roughly speaking, I wanted it to work like this:

$('div').clickOut(); // Forma normal

// Forma que tentei, e não deu certo.
$('#my-uls').on('clickOut', 'li', function (...){}); 
    
asked by anonymous 16.10.2015 / 16:14

3 answers

2

In fact, Emir Marques's answer hit the beam. The path is yes trigger , which is required to trigger the event. Every event fired with trigger can be captured with on . So:

(function ( $ ) {

    $(document).click(function (e) {
        if ($(e.target).closest(that).size() > 0) {
            $(e.target).trigger('clickOut');
            return;
        }
    });

    // Feito isso, você pode usar:
    $('#my-uls').on('clickOut', 'li', function (){
        // faz algo
    }); 

})( jQuery )
    
16.10.2015 / 17:55
0

For this you can use the trigger method.

In this case instead of using:

 $(<seletor>).on("clickOut", function(){
     /* Faz algo */
 });

You use:

 $(<seletor>).trigger("clickOut", function(){
    /* Faz algo */
 });

Full example:

(function ( $ ) {

    $.fn.clickOut = function (callback) {

        var that = this;

        $(document).click(function (e) {

            if ( $(e.target).closest(that).size() > 0) {

                return;
            }

            $.isFunction(callback) && $.proxy(callback, that)(e);
        });
    }

    $(<seletor>).trigger("clickOut", function(){
        /* Faz algo */
    });

})( jQuery )
    
16.10.2015 / 16:27
0

So I understand the question, you want to create a callback so that after executing the .on event it executes its clickOut function.

For this you must call it inside the function.

(function($){
    $.fn.alertX = function(x){
        alert(x)
    }
})(jQuery);

jQuery('body').on('click', 'input', function(){
    var id = jQuery(this).attr('id');
    jQuery(this).alertX(id);
});

Example

NOTE: I am still seeing if you can always do this in the method, type prototype.

    
16.10.2015 / 18:14