简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM