我最近正在研究小型聊天模块,该模块需要不断检查服务器是否有新消息。
我正在向服务器发送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
对象传递给complete
jquery的参数
所以我想要的是将参数传递给jQuery
complete
函数的方法,以便它指向我的原始引用
$.proxy
:我认为这是最佳做法。
$.ajax({
//...
success: $.proxy(function(json) {
// `this` refers to the second argument of `$.proxy`
}, this)
});
context
选项:$.ajax({
//...
context: this,
success: function(json) {
// `this` refers to the value of `context`
}
});
var self = this;
$.ajax({
//...
success: function(json) {
// `this` refers to ajax request, use self instead
$(self).dosomething();
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句