【发布时间】:2014-09-03 06:04:42
【问题描述】:
我最近在做一个小聊天模块,需要不断检查服务器是否有新消息。
我正在向服务器发送一个 ajax 请求,服务器保持连接直到找到新消息(长轮询)。
代码:
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
});
当我试图打电话时
var mainController = new chatController();
mainController.checkNewMessage();
问题
我以为我可以向服务器发送连续的单个请求,但令我惊讶的是,我只能一个接一个地发送 2 个 ajax 请求。
我的调试
当我尝试调试时,我发现第一次调用 this 传递的对象指向 chatController
complete: (function(obj){
return obj.checkNewMessage;
})(this), // this here point to chatController object
this 对象第二次指向ajax object
complete: (function(obj){
return obj.checkNewMessage;
})(this), // this here point to ajax object
我正在使用 JavaScript 闭包将 chatController 对象传递给 jquery 的 complete 参数
所以我想要的是将参数传递给jQuery complete 函数的方法,以便它指向我的原始参考
【问题讨论】:
-
您可以将“this”定义为变量然后使用它。像 var $thisChatController = this;
-
@SohilDesai 能给我举个例子吗,谢谢
-
@Parfait 我想在回调中传递相同的对象函数
-
您可以使用 Signal R 来实现它,这是 .net codeproject.com/Articles/524066/… 中的聊天应用程序示例,如果您使用其他语言,您也可以将其集成......
标签: javascript jquery ajax