I have a problem using Class with setter using ajax. Here is the condition.
var MyClass = Class.create();
MyClass.prototype = {
myAttr:0,
setMyAttr: function(){
jQuery.ajax({
url:'data.php',
success:function(data) {
//set myAttr here
}
});
}
}
I want to set myAttr inside the success function, how to do this? Thanks. 😀
You haven’t said what
Class.createis (there is none in JavaScript itself), but I don’t think it matters much for the question.I assume you want to set
myAttron the instance, not the prototype (but see below if I’m wrong). The simplest way is to take advantage of the fact that yoursuccesscallback is already a closure over the context of the call tosetMyAttr, so you set a variable to bethis(sincethiswill be different in thesuccesscallback) and use that:More on closures: Closures are not complicated
But if I’m wrong and you do actually want to update the prototype instead:
(Note the
;at the end of the assignment to the prototype. I strongly advocate not relying on the horror that is automatic semicolon insertion.)