0

How do I get this into a callback?

Started out with this, worked.

$('#grid').w2grid({
  name : 'grid',
// Lost of setup
  onMenuClick: function(event) {
    $.getJSON('?json=json&action=E&id=' + event['recid'], function(data) {
//    do some work
    });
    this.reload();
  },
});

Then to only call reload if the request worked.

$('#grid').w2grid({
  name : 'grid',
// Lost of setup
  onMenuClick: function(event) {
    $.getJSON('?json=json&action=E&id=' + event['recid'], function(data) {
//    do some work
      this.reload();
    });
  },
});

Of course "this" is no longer references the object I want to access.

Or how would I gain access the parent object?

Jason K
  • 1,406
  • 1
  • 12
  • 15
  • 2
    arrow function or store the `this` in another variable and use that variable. This question is a duplicate. – Taplar Mar 18 '19 at 20:04
  • https://stackoverflow.com/questions/41496958/this-does-not-work-properly-in-another-event-im-clueless-as-to-why/41496969#41496969 – Scott Marcus Mar 18 '19 at 20:04

2 Answers2

0

You may just bind your this inside the callback.

Note: Beware of any side-effects. Apparently you don't seem to need the new this inside the callback.

Try:

$('#grid').w2grid({
  name: 'grid',
  onMenuClick: function(event) {
    $.getJSON('?json=json&action=E&id=' + event['recid'], (function(data) {
      this.reload();
    }).bind(this));
  }
});

When arrow-functions are available, I'd suggest to use them rather than binding this.

jankal
  • 1,090
  • 1
  • 11
  • 28
0

You can do it like this:

let parent = this;
$.getJSON('?json=json&action=E&id=' + event['recid'], function(data) {
//    do some work
      parent.reload();
    });
jare25
  • 506
  • 1
  • 7
  • 17