linuxeasy
linuxeasy

Reputation: 6499

Accessing Object variables in a callback

I have a following design

function crudDataTable()
{
    this.addEditFormContainerSelector = ''; 
    this.paginationType = "full_numbers";  // Provide Pagination Type
    this.processing = true; 
    this.serverSide = true;  //I want this this to be accessible in fnRowCallback below:

    this.create = function(){

        this.tableInstance = $(this.tableLocationSelector).DataTable({
            "sPaginationType": this.paginationType
            fnRowCallback:function(nRow, aData) {
                // "this" from crudDataTable should be accessible here
            }  
        })
    }
}

I want the this from crudDataTable to be accessible in fnRowCallback.

How can I acheive this?, also the fnRowCallback is fired by the datatable component, so that's not in my control. How can I make this accessible under fnRowCallback.

Or if this is not possible, then what are the other approaches to achieve it?

I am trying to write a component, where users of these component can simply setup its variables and call the create function. I am facing this challenge of accessing this in the fnRowCallback function.

Thanks.

Upvotes: 0

Views: 397

Answers (1)

James Allardice
James Allardice

Reputation: 166051

You can store a reference to this outside of the callback:

var table = this;
this.tableInstance = $(this.tableLocationSelector).DataTable({
     "sPaginationType": this.paginationType,
     fnRowCallback: function(nRow, aData) {
         //Use `table` to refer to the instance of `crudDataTable`
     }  
});

Alternatively, you can use the ES5 bind method (but be aware that older browsers don't support it):

this.tableInstance = $(this.tableLocationSelector).DataTable({
     "sPaginationType": this.paginationType,
     fnRowCallback: function(nRow, aData) {
         //Use `this` to refer to the instance of `crudDataTable`
     }.bind(this);
});

Upvotes: 2

Related Questions