Why did I need to pass this as a function parameter?

Asked

Viewed 26 times

0

I tried to put a piece of code for a function, to repurpose the code, it worked, only I had to pass the this as a parameter, I do not know if it is correct to do this.

Follow the code as it was and as I left it:

// como estava
$(document).ready(function() {
    $('table').dataTable({

        // code ...

        "drawCallback": function ( settings ) {

            var api = this.api();
            var rows = api.rows( {page:'current'} ).nodes();
            var last=null;

            api.column(0, {page:'current'} ).data().each( function ( group, i ) {
                if ( last !== group ) {
                    $(rows).eq( i ).before(
                        '<tr class="info"><td colspan="2">'+group+'</td></tr>'
                    );

                    last = group;
                }
            } );

            // code ...
        }
    });
});

and how I left

//como deixei
$(document).ready(function() {
    $('table').dataTable({

        // code ...

        "drawCallback": function ( settings ) {

            groupColumnToRowDT(this, 0, 2);

            // code ...
        }
    });
});

and the function I created

function groupColumnToRowDT(t, column, colspan) {
    var api = t.api();
    var rows = api.rows( {page:'current'} ).nodes();
    var last=null;

    api.column(column, {page:'current'} ).data().each( function ( group, i ) {
        if ( last !== group ) {
            $(rows).eq( i ).before(
                '<tr class="info"><td colspan="'+colspan+'">'+group+'</td></tr>'
            );

            last = group;
        }
    } );
}
  • 1

    Well, to pass the datatable as a function parameter.

  • okay, but it’s right then the way I did?

  • It works the way it should?

  • it works, but it seemed to me a gambiarra, I did, I tested, it worked, but I kept taking a look and it didn’t seem the most beautiful thing...

  • 1

    If it works the way it should, that’s right. You should probably be used to the this in other programming languages. In Javascript the story changes a little, so the strangeness.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.