Object in object

var UsersMenu = function(){
    this.returnUsers = [];
    this.retrieve = function(posts){
        var temp = [];
        $.post("router.php", { "action": "getUsersMenu", "posts" : posts},
        function(data)
        {
            if(data.response){    
                for(var i=0; i<data.returnUsers.length; i++){
                    temp.push(data.returnUsers[i]);
                }
                this.returnUsers = temp; // i know what 'this' is incorrect
            }

        }, "json");
                alert(this.returnUsers);
    }
}

2 questions:
1. How to access the parent object 'this' from the jq object (returnUsers)?
2. Why is the warning after the jq message is called before some warning in the jq message?

+5
source share
5 answers

1 How to access the parent 'this' object from a jq (returnUsers) object?

You can lock it in closing:

var UsersMenu = function() {
    this.returnUsers = [];
    var self = this;
    this.retrieve = function(posts) {
        var temp = [];
        $.post("router.php", { "action": "getUsersMenu", "posts" : posts },
        function(data) {
            if(data.response) {
                for(var i = 0; i < data.returnUsers.length; i++) {
                    temp.push(data.returnUsers[i]);
                }
                self.returnUsers = temp;
            }
        }, "json");
    }
};

2 Why is the warning after the jq message is called before some warning in the jq message?

AJAX . $.post, AJAX, , , . . AJAX, , .

+5
  • 'this' jq (returnUsers)?

'this' var self = this; , self.returnUsers = temp;.

  • , jq jq?

ajax , jQuery.ajax async: false.

+2

: $.post() Ajax. , $.post() , , alert(). , Ajax , $.post(), , , alert() , .

: this , , jQuery , , , , UserMenu . - this , retrieve(), :

var UsersMenu = function(){
    this.returnUsers = [];
    this.retrieve = function(posts){
            var self = this,
            temp = [];
            $.post("router.php", { "action": "getUsersMenu", "posts" : posts},
            function(data)
            {
               if(data.response){    
                   for(var i=0; i<data.returnUsers.length; i++){
                       temp.push(data.returnUsers[i]);
                   }
                   self.returnUsers = temp;
                }               
            }, "json");
            alert(this.returnUsers);
    }
}

, retrieve() Ajax, JavaScript , .

+2

.

, jq jq?

AJAX , , AJAX . . " " - alert.

, AJAX , alert.

0

1 - that

var that = this.returnUsers; 

jq funciton :

  if(data.response){
       for(var i=0; i<data.returnUsers.length; i++){
             temp.push(data.returnUsers[i]);
       }
          that = temp; // Now 'this' is correct
  }

2 - This is because ajax calls are asynchronous by default, meaning that the javascript interpreter will not wait for the ajax call to complete and will continue to execute the following statements, so put a warning in the callback function.

0
source

All Articles