Why does footerCallback function only allow this.api()?
Why does footerCallback function only allow this.api()?
hzhong
Posts: 22Questions: 8Answers: 0
in DataTables
Hello,
Here is a short example using the API to sum a specific column and output in the footer. I have couple questions. Would someone help me understand?
var table = $('#example').DataTable( {
"footerCallback": function( tfoot, data, start, end, display ) {
var api = this.api();
$( api.column( 5 ).footer() ).html(
api.column( 5 ).data().reduce( function ( a, b ) {
return a + b;
}, 0 )
);
}
} );
- Why does footerCallback function only allow this.api() as the api instance? I tried using
table
variable but failed, which is also an api instance right? - I assume this.api() is an implementation of $( selector ).dataTable().api(). But why does
this
keyword refer to the dataTable object, not just the object passed in the constructor?
Thank you.
This question has accepted answers - jump to:
Answers
That's really just standard JavaScript questions.
table
is assigned once the initialisation has completed, so at the point it's called infooterCallback
it would still be initialised.this
is the context within the callback function - sothis.api()
is there to assist with the issue in your first question,Colin
Thanks Colin. I understand the first point now. I'm still trying to understand the second one.
I thought
this
in the callback referred to the below object which was passed to the table initialization. I still don't get it why it's resolved to same as$(#example).dataTable()
.Thank you for your time. You can also point me to some useful resource I can refer.
In
footerCallback
the scope ofthis
is thetable
element. We add anapi()
method to that to allow access to the DataTables API in the callback.Ideally the scope would just be the DataTables API, but it isn't for legacy reasons. The API (as it currently is) was added in 1.10, while
footerCallback
was added long before then, so I followed standard jQuery practice and made the scope of the function the element.It might be changes at some point, but I try very hard to not break backwards compatibility, so more likely this will stay as is, and a new callback or event will be used with the API scope.
Allan
Hello Allan,
Thank you for the answer. Maybe I missed something in standard JavaScript as I am still confused why
this
is resolved to the jQuery object, not the options object passed in the initialization as I thought.If I have a simplified object
a
as belowThen I call the method
a.footerCallback()
. The log result is the objecta
.But why is it after I passed this
a
as the options object into the datatable initialization astable = $('#example').DataTable( a )
,this
resolved to datatable object?Thanks.
Thanks Allan. I'm clear now. Please disregard the last comment.