0

I have a question regarding the ajax callback function

I have

test = function(){
  this.items=[];
}

//original state.
test.prototype.getListItems = function (){

    this.items.push('test item');
    this.handleItems();

}

//this method will be called if the user clicks a button.
test.prototype.clickBtn = function (){

    this.ajGetOneMoreItem()    
    this.handleItems();
}

//a callback function that will add a new item.
test.prototype.ajGetOneMoreItem = function (){
   var that=this;    
     ajax.callback = function(dataItem){
         that.items.push(dataItem);
     }    
}

//to show the items.
test.prototype.handleItems = function (){

       //only show the test item, but not dataItem after user clicks a button.
      console(this.items)

}


var testObj = new test();

$('#testBtn).click(function(){
   testObj.clickBtn();
})

I want to show the new items that was added through the user. However, it only appears this.items only show the first 'test item' but did not add the new dataItem. Am I missing something here? Thanks a lot!

FlyingCat
  • 14,036
  • 36
  • 119
  • 198
  • Your AJAX call is likely asynchronous. This means `this.handleItems()` will run before the AJAX responds with the new data. Do some logging in various places like your callback, and you'll see that the code runs out of order. –  Apr 05 '13 at 22:38
  • 1
    This must be the question of the century with hundreds of duplicates. – elclanrs Apr 05 '13 at 22:38

1 Answers1

0

The invocation of:

this.ajGetOneMoreItem();

completes almost instantly. This means the next step:

this.handleItems();

happens before the AJAX callback has been executed. To solve this problem, move the second step into the callback.

test.prototype.ajGetOneMoreItem = function (){
   var that=this;    
     ajax.callback = function(dataItem){
         that.items.push(dataItem);
         that.handleItems();
     }    
}
Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
  • `this.handleItems();` will likely fail because `this` is most likely redefined. And `$('#testBtn').click(testObj.clickBtn);` is wrong because the method loses its reference to `testObj`. OP is doing it correctly. –  Apr 05 '13 at 22:53