开发者

JavaScript: Assign an object to another object

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜