在jQuery中将对象传递给回调函数 [英] passing object to callback function in jquery
问题描述
我最近正在研究小型聊天模块,该模块需要不断检查服务器中是否有新消息.
I am recently working on small chat module , which require continuously checking the server for new message.
我正在向服务器发送ajax请求,并且服务器保持连接状态,直到找到新消息为止(长时间轮询).
I am sending a ajax request to a server , and the server hold's the connection until new message is found(long polling).
代码:
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请求.
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.
我的调试
当我尝试调试时,我发现传递的第一个调用this
对象指向chatController
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
第二次传递的this
对象指向ajax 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
我正在使用JavaScript闭包将chatController
对象传递给jquery的complete
参数
I am using JavaScript closure to pass the chatController
object to complete
parameter of jquery
所以我想要的是将参数传递给jQuery
complete
函数的方法,以便它指向我的原始引用
So what i want is way to pass parameter to jQuery
complete
function so that it's point to my original reference
推荐答案
有各种可能的跨浏览器解决方案
您可以使用> $.proxy
:
我认为是最佳做法.
There are various posible cross-browser solutions
You can use $.proxy
:
In my opinion, the best practice.
$.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();
}
});
这篇关于在jQuery中将对象传递给回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!