0

how would i do this?

function DoStuffAndCallBack(callback){
      $.get( "ajax/test.html", function( data ) {
      callback();

    });
}

DoStuffAndCallBack(DoneFunction);

function DoneFunction(){
  console.log('done stuff');
}

I am getting 'callback' as undefined.Is there a way to do this, i know there are promises and what not but how can i do this in this instance.

Aflred
  • 4,435
  • 6
  • 30
  • 43

1 Answers1

-2

It looks like the "callback" is loosing its context inside your inner function i.e. inside the ajax call.

Try this -

function DoStuffAndCallBack(callback){
    this.callback = callback;
    var self = this;
    $.get( "ajax/test.html", function( data ) {
      self.callback();
    });
}

DoStuffAndCallBack(DoneFunction);

function DoneFunction(){
  console.log('done stuff');
}
Nitesh Goyal
  • 586
  • 5
  • 11
  • Why would it loose its context? – putvande Jun 06 '16 at 12:24
  • Please refer [this](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback) Here it is very well explained. In case of call backs we need to explicitly set the 'this' – Nitesh Goyal Jun 06 '16 at 12:26