2013-11-29 2 views
2

Ниже приводится сценарий:Как передать контекст сделано в Ajax

getSomething: function(){ 
    var gotValue = sendAjax(); 
    gotValue.done(function(response){ 
     console.log(response); //How to pass context of object to call getSomethingElse 
     //getSomethingElse(); 
    }); 
}, 
getSomethingElse : function(){ 
} 

Я хочу, чтобы вызвать функцию getSomethingElse в проделанного методом Аякса

+0

Вы можете использовать apply, call для передачи ссылки на объект. Если вы всегда хотите, чтобы getSomethingElse вызывался с некоторой ссылкой. Используйте bind https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind – sachinjain024

+0

возможный дубликат [Как получить доступ правильный \ 'этот \'/контекст внутри обратного вызова?] (http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback) –

ответ

2

Использование $this=this; поскольку this в функции не ссылаясь на объект.

getSomething: function() 
{ 
var $this = this; 
var gotValue = sendAjax(); 
gotValue.done(function(response){ 
    console.log(response); 
    $this.getSomethingElse(); 
}); 
}, 
getSomethingElse : function() 
{ 
} 

Или вы можете использовать $.proxy

gotValue.done($.proxy(function(response){ 
    console.log(response); 
    this.getSomethingElse(); 
},this)); 
0

Используя ссылку на текущий контекст:

getSomething: function() { 
    var self = this; 
    sendAjax().done(function (response) { 
     self.getSomethingElse(response); 
    }); 
    // or even shorter: sendAjax().done(self.getSomethingElse); 
}, 
getSomethingElse: function() {} 

Использование bind метод:

getSomething: function() { 
    sendAjax().done(function (response) { 
     this.getSomethingElse(response); 
    }.bind(this)); 
}, 
getSomethingElse: function() {} 
0

Попробуйте это:

var someHelper = { 

    getSomething : function() { 

     var gotValue = sendAjax(); 

     //keep a reference to the obj, normally "this", or "someHelper" 
     var self = this; 

     gotValue.done(function(response) { 

      console.log(response); //How to pass context of object to call getSomethingElse 
      //getSomethingElse(); 

      //call getSomethingElse 
      self.getSomethingElse(); 
     }); 
    }, 
    getSomethingElse : function() { 

    } 
} 
Смежные вопросы