Define the prototype attribute using ajax jquery

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. :D

You haven't said what Class.create is (there is none in JavaScript itself), but I don't think it matters much for the question.

I assume you want to set myAttr on the instance , not the prototype (but see below if I'm wrong). The simplest way is to take advantage of the fact that your success callback is already a closure over the context of the call to setMyAttr , so you set a variable to be this (since this will be different in the success callback) and use that:

var MyClass = Class.create();
MyClass.prototype = {
    myAttr:0,
    setMyAttr: function(){
        var self = this;            // <== Set the variable
        jQuery.ajax({
            url:'data.php',
            success:function(data) {
                self.myAttr = data; // <== Use it
            }
        });
    }
};

More on closures: Closures are not complicated

But if I'm wrong and you do actually want to update the prototype instead:

var MyClass = Class.create();
MyClass.prototype = {
    myAttr:0,
    setMyAttr: function(){
        jQuery.ajax({
            url:'data.php',
            success:function(data) {
                MyClass.prototype.myAttr = data;
            }
        });
    }
};

(Note the ; at the end of the assignment to the prototype. I strongly advocate not relying on the horror that is automatic semicolon insertion.)

我来评几句
登录后评论

已发表评论数()

相关站点

+订阅
热门文章