开发者

JavaScript: Assign an object to another object

开发者 https://www.devze.com 2023-04-06 13:17 出处:网络
I\'m trying to assign the local var UgcItems to uploadedItems but when I try to return the value I get undefined.If I put the console.log inside of the .getJSON then I get the appropriate value.The pr

I'm trying to assign the local var UgcItems to uploadedItems but when I try to return the value I get undefined. If I put the console.log inside of the .getJSON then I get the appropriate value. The problem with that is that the scope is inside of the function. What can I do to get the JSON out of the functi开发者_开发技巧on?

$(function(){
    var uploadedItems;
    $.getJSON("GetExistingUgcItems?workItemId=1", function (UgcItems) {
        uploadedItems = UgcItems;
    });

    console.log(uploadedItems);
});

Thank you,

Aaron


The problem you're experiencing is that getJSON executes asynchronously by default. So the assignment to uploadedItems happens after the console.log(uploadedItems) command completes.

Instead of defining uploadedItems in the root function, define a method which takes uploadedItems. Put all of the code which uses uploadedItems in this function and call it from the completed handler

var withUploadedItems = function(uploadedItems) {
  console.log(uploadedItems);
  // etc ...
};

$.getJSON("GetExistingUgcItems?workItemId=1", function (UgcItems) {
  uploadedItems = fromJSON(toJSON(UgcItems));
  withUploadedItems(uploadedItems);
});
0

精彩评论

暂无评论...
验证码 换一张
取 消