I am trying to set up a callback in jQuery that correctly binds "this" to the calling object. Specifically, here is the code I am working with. I am doing an ajax call in a Object like this:
我正在尝试在jQuery中设置一个回调,以正确地将“this”绑定到调用对象。具体地说,这是我正在处理的代码。我正在这样的对象中执行ajax调用:
Object.prototype.doAjaxCall = function(url)
{
$.get(url, null, this.handleAjaxResponse );
}
However, in Object.prototype.doAjaxCall
, this
does not refer to the correct thing. I have worked with Prototype before and I know you need to bind this when you do the Ajax call, but I can't seem the find the correct way to do that in jQuery. Can someone point me in the right direction?
然而,在Object.prototype。doAjaxCall,这不是指正确的东西。我以前使用过Prototype,我知道在执行Ajax调用时需要绑定它,但是我似乎无法找到正确的方法来使用jQuery。有人能给我指出正确的方向吗?
2 个解决方案
#1
1
A more robust, native bind function should be part of ECMAScript 3.1. In the meantime...
更健壮的本机绑定函数应该是ECMAScript 3.1的一部分。与此同时……
Object.prototype.doAjaxCall = function(url) {
var bind = function(context, method) {
return function() {
return method.apply(context, arguments);
};
};
$.get(url, null, bind(this, this.handleAjaxResponse));
};
#2
2
Use the jQuery ajax context
property to bind this. eg:
使用jQuery ajax上下文属性绑定它。例如:
$.ajax({
context: this,
url: url,
type: 'GET'
}).done( function(data, textStatus, jqXHR) {
this.handleAjaxResponse();
});
#1
1
A more robust, native bind function should be part of ECMAScript 3.1. In the meantime...
更健壮的本机绑定函数应该是ECMAScript 3.1的一部分。与此同时……
Object.prototype.doAjaxCall = function(url) {
var bind = function(context, method) {
return function() {
return method.apply(context, arguments);
};
};
$.get(url, null, bind(this, this.handleAjaxResponse));
};
#2
2
Use the jQuery ajax context
property to bind this. eg:
使用jQuery ajax上下文属性绑定它。例如:
$.ajax({
context: this,
url: url,
type: 'GET'
}).done( function(data, textStatus, jqXHR) {
this.handleAjaxResponse();
});