0

ajax callback我对函数有疑问

我有

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();
})

我想显示通过用户添加的新项目。但是,似乎 this.items 只显示了第一个 ' test item' 而没有添加新的dataItem。我在这里错过了什么吗?非常感谢!

4

1 回答 1

0

调用:

this.ajGetOneMoreItem();

几乎立即完成。这意味着下一步:

this.handleItems();

在执行 AJAX 回调之前发生。为了解决这个问题,将第二步移到回调中。

test.prototype.ajGetOneMoreItem = function (){
   var that=this;    
     ajax.callback = function(dataItem){
         that.items.push(dataItem);
         that.handleItems();
     }    
}
于 2013-04-05T22:42:08.243 回答