1

I have a function within the component and at the same time I am using DataTables button to trigger display a modal. Here's the snippet:

constructor(props) {
      super(props);
      this.state = {
          error: null,
          isLoaded: false,
          table_type: 'default',
          date_time : null,
          data: [],
          header : null
      };
      this.toogleBtnTbl = this.props.toogleBtnTbl.bind(this);
      this.showModal = this.props.showModal.bind(this);
    }

I cant call the function this.showModal inside the button of Datatables because this refers to the Datatables in this case. My question is how to call this.showModal inside the action property?

buttons: [
                {
                    text: 'View in Graph',
                    action: function ( e, dt, node, config ) {  
                        this.showModal();//not working undefined
                    }
                },
2
  • const show = this.Modal(); then call show() Commented Mar 6, 2018 at 1:39
  • Where would I put that? Commented Mar 6, 2018 at 1:41

2 Answers 2

1

You must change to arrow funcion

action: ( e, dt, node, config ) => {  
   this.showModal();
}
Sign up to request clarification or add additional context in comments.

4 Comments

Ahh ok, care to explain this? The suggestion of @Omar also works by assigning it in a variable.
in arrow function you can direct call "this". instead of doing like var self = this and call self.showModal()
How come that its calling the component's this.showModal() function and not the this inside it?
You can readmore at exploringjs.com/es6/…
0

Never used DataTables but I think you just need an anonymous immediately executed function to capture "this" and store it in a closure:

buttons: [
            {
                text: 'View in Graph',
                action: (function(component){
                    return function ( e, dt, node, config ) {  
                        component.showModal();
                    };
                })(this);
            },

action is being set to a function which is immediately called storing 'this' inside it's own little lexical environment where the returned function will always have access to it. Let me know if this works.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.