11

So I am using a uikit confirmation modal in my app. My problem is, when I am going to click the <button> for confirmation. the this inside function is undefined. here's my code...

declare var UIkit:any;

deleteData(dataArr): void {

    UIkit.modal.confirm('Are you sure you want to delete this?', function() {
      console.log(dataArr);
      console.log(this);
      //use service here...
      UIkit.modal.alert('Confirmed!');  
    });
}

Inside that function I wish to use service for http request but I am having a problem on the this. I am using Angular 2.x.

scniro
  • 16,844
  • 8
  • 62
  • 106
Joshua Fabillar
  • 506
  • 2
  • 9
  • 24
  • 1
    `() => {` ... ... – Kevin B Jun 22 '17 at 15:47
  • Possible duplicate of [setTimeout and "this" in JavaScript](https://stackoverflow.com/questions/591269/settimeout-and-this-in-javascript) | https://stackoverflow.com/questions/34930771/why-is-this-undefined-inside-class-method-when-using-promises – Kevin B Jun 22 '17 at 15:53

2 Answers2

17

Use an arrow function...

declare var UIkit:any;

deleteData(dataArr): void {

  UIkit.modal.confirm('Are you sure you want to delete this?', () => {

    console.log(this);
    // [...]
  });
}

Check out MDN: Arrow functions for details on the matter.

An arrow function does not create its own this context, so this has its original meaning from the enclosing context.

scniro
  • 16,844
  • 8
  • 62
  • 106
  • wow. that was pretty easy. i thought im going to use bind. anyway thank you. it worked now – Joshua Fabillar Jun 22 '17 at 15:59
  • What if you have a common function like a string filter on one of many arrays, with the same global input var? I've got 5 lists I can add/remove things from. When removing, I want to use array.filter(my_class_filter_func()). But the call to my_class_filter_func() gives "this" is null or undefined. Any thoughts? – patrickjp93 Mar 03 '19 at 06:08
0

'this' is not passed to your function scope, try

declare var UIkit:any;

deleteData(dataArr): void {
var that = this;
UIkit.modal.confirm('Are you sure you want to delete this?', function(){
  console.log(dataArr);
  console.log(that);
  //use service here...
  UIkit.modal.alert('Confirmed!');  
});
}