zzmaster
zzmaster

Reputation: 317

Local variable not visible in javascript callback function

I have a number of pages with sortable columns, the code is like

            var invert = $('...').val();
            var column = $('...').val();
            $list.children().detach().sort(function (a,b) { 
                var aa = $(a).find('.'+column).html().trim();
                var bb = $(b).find('.'+column).html().trim();
                // conversions cut off
                return invert ? aa-bb : bb-aa;
            }).appendTo($list);

where column is a class of the column to sort. I'd like to make it one callback function instead of repeating the code

function column_sorter(a, b) {
    var aa = $(a).find('.'+column).html().trim();
    // ....
}

$list.children().detach().sort(column_sorter).appendTo($list);

but column is inaccessible here (and invert probably - too). Is there any possibility to utilize the function here?

Upvotes: 0

Views: 154

Answers (2)

Nitheesh
Nitheesh

Reputation: 19986

Its as simple as this

function sort_function(a, b, c) {
  console.log(c);
  return a - b;
}
const arr = [4, 1, 5, 3, 2];
c = "test";
arr.sort((a, b) => sort_function(a, b, c));
console.log(arr);

So you could use it as

function column_sorter(a, b, c) {
    var aa = $(a).find('.'+column).html().trim();
    // ....
}

$list.children().detach().sort((a, b) => column_sorter(a, b, c)).appendTo($list);

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074148

Is there any possibility to utilize the function here?

You'll have to pass that contextual information to the function. Often the way to do that is to have a function that returns another function, and have sort call the returned function:

function column_sorter(column/*, ...anything else it needs...*/) {
    return function(a, b) {
        var aa = $(a).find('.'+column).html().trim();
        // ....
    };
}

$list.children().detach().sort(column_sorter(column/*, ...*/)).appendTo($list);

Side note: If the function need this to be controlled by sort (usually it doesn't), I'd probably make it an arrow function:

function column_sorter(column/*, ...anything else it needs...*/) {
    return (a, b) => {
        var aa = $(a).find('.'+column).html().trim();
        // ....
    };
}

$list.children().detach().sort(column_sorter(column/*, ...*/)).appendTo($list);

Upvotes: 4

Related Questions