chalo
chalo

Reputation: 1059

Make a custom function from event on click

regards, I need to create a custom function to the next event, I will need future use in other similar situations.

Fiddle example

For example a have:

$('a.trigger').on('click', function (e) {
    e.preventDefault();
    var dataTrigger = $(this).attr('data-trigger');
        $(this).find('i').toggleClass( 'fa-plus-square fa-minus-square'); //Cambia el icono

    if ($('div[data-container="' + dataTrigger + '" ]').length) {
        var elem = $('[data-container="' + dataTrigger +'"]');
        elem.toggle();
    }
});

Transform the click event to:

var showTables = function (){
    e.preventDefault();
    var dataTrigger = $(this).attr('data-trigger');
    $(this).find('i').toggleClass( 'fa-plus-square fa-minus-square'); //Cambia el icono

    if ($('div[data-container="' + dataTrigger + '" ]').length) {
        var elem = $('[data-container="' + dataTrigger +'"]');
        elem.toggle();
    }
}

I need call something like this:

$('a.trigger').on('click', function (e) {
   showTables();
});

How can you do?

Upvotes: 0

Views: 44

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue with calling the function like this is that you lose the context of this within the showTables function. You have two options. Firstly, you could pass it as a parameter:

$('a.trigger').on('click', function (e) {
    e.preventDefault();
    showTables(this);
});

var showTables = function (that) {
    // your code, changing references of 'this' to 'that'
}

Alternatively you can leave the showTables as it is now and give the function reference to the handler to maintain the scope:

$('a.trigger').on('click', showTables);

The latter is preferable where possible due to its' brevity.

Upvotes: 1

Rhumborl
Rhumborl

Reputation: 16609

Just reference the existing function in your click, rather than creating a new one:

$('a.trigger').on('click', showTables);

Upvotes: 0

Related Questions