You should be able to specify the this
value as the context in your $.ajax()
parameters:
var c$ = {};
c$.TestScope = function() {
this.doAjax = function(onComplete) {
alert('doAjax1 this === c$.oTestScope: ' + (this === c$.oTestScope).toString());
$.ajax({
url: 'badurl',
context: this,
complete: function(data) {
alert('doAjax2 this === c$.oTestScope: ' + (this === c$.oTestScope).toString());
onComplete.call(this, data);
}
});
};
this.doStuff = function(data) {
alert('doStuff this === c$.oTestScope: ' + (this === c$.oTestScope).toString());
}
};
c$.oTestScope = new c$.TestScope();
c$.oTestScope.doAjax(c$.oTestScope.doStuff);
Edit I made a fiddle for this and verified that it works properly. There's no messing around with an extra self
parameter or having to muck around with closures to keep your variables.
Part of what you were missing was calling onComplete.call(this, data)
to invoke doStuff()
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…