Skip to main content
Stack Overflow
  1. About
  2. For Teams

Return to Question

Post Timeline

Commonmark migration
Source Link
Source Link
sanjeev
  • 4.7k
  • 2
  • 22
  • 28

passing object to callback function in jquery

I am recently working on small chat module , which require continuously checking the server for new message.

I am sending a ajax request to a server , and the server hold's the connection until new message is found(long polling).

Code :

var chatController = function(){
 
//other variable declaration
/**
* Ajax call to monitor the new message , on complete of ajax call sending other call
*/
this.checkNewMessage = function(){
 console.log(this); // placed this for debugging purpose
 $.ajax({
 url : SITEURL.CHECK_MESSAGE,
 data : this.currrentUserDetails,
 dataType : 'json' ,
 cache : false,
 success :(function(obj){
 //temp = obj;
 return obj.parseNewMessageResponse;
 })(this),
 complete: (function(obj){
 //temp = obj;
 return obj.checkNewMessage;
 })(this), 
 });
 
 
};
 // other function and variable
});

When i tried to call

var mainController = new chatController();
mainController.checkNewMessage();

Problem

What i thought was that i would be able to send continuous single request to server, but to my surprise I only could send 2 ajax request one after the other.

My Debugging

When i tried to debug , i traced out that for the first call this object being passed points to the chatController

 complete: (function(obj){
 return obj.checkNewMessage;
 })(this), // this here point to chatController object
 
 

For the second time this object being passed points to the ajax object

 complete: (function(obj){
 return obj.checkNewMessage;
 })(this), // this here point to ajax object

I am using JavaScript closure to pass the chatController object to complete parameter of jquery

So what i want is way to pass parameter to jQuery complete function so that it's point to my original reference

lang-js

AltStyle によって変換されたページ (->オリジナル) /