Espen
Espen

Reputation: 3727

JavaScript object going out of scope

namespace.items.Load = function (arg1, arg2) {
    $.getJSON("/Object/Items", { "Arg1": arg1, "Arg2": arg2 }, function (Items) {
        return Items;
    });
}

Do the above object "Items" go out of scope or something? Because after calling this function all I get is "undefined". How can I fix this?

Upvotes: 1

Views: 302

Answers (4)

user1636522
user1636522

Reputation:

First, there is no return statement inside the Load function. In this case, it will return undefined by default. There is nothing unexpected so far, but I guess you rather wanted to do things like that :

namespace.items.Load = function (arg1, arg2) {
    return $.getJSON(
        "/Object/Items", 
        { "Arg1": arg1, "Arg2": arg2 }, 
        function (Items) { return Items; }
    );
}

That said, keep in mind that there is an Ajax call behind the scene which results in this kind of scenario :

  1. Load function is called.
  2. An Ajax request is sent to a remote server.
  3. Load function returns.
  4. An Ajax response is sent back.
  5. function (Items) { return Items; } is called.

What you were expecting to be returned by the Load function is obviously not Items. Thereby, you might use this kind of solution instead : https://stackoverflow.com/a/18793057/1636522.

Upvotes: 1

Andy
Andy

Reputation: 63524

$.getJSON implements the promise interface, so you should be able to do this:

namespace.items.Load = function (arg1, arg2) {
  return $.getJSON("/Object/Items", { "Arg1": arg1, "Arg2": arg2 });
}

namespace.items.Load().then(function (items) {
  console.log(items);
});

Upvotes: 1

Björn
Björn

Reputation: 29381

The getJSON request is asynchronous, so you'll have to provide a callback to your items.Load function as well.

namespace.items.Load = function (arg1, arg2, callback) {
    $.getJSON("/Object/Items", { "Arg1": arg1, "Arg2": arg2 }, callback);
};

Upvotes: 2

BenM
BenM

Reputation: 4278

AJAX methods return instantly so then will return undefined. You need to specify a callback function if you want to use those "Items" results such as assigning them to a variable which can be accessed by other functions in your namespace.

namespace.itemList = {};

namespace.items.Load = function (arg1, arg2) {
$.getJSON("/Object/Items", { "Arg1": arg1, "Arg2": arg2 }, function (Items) {
    namespace.itemlist = JSON.parse(Items);
});
}

Upvotes: 0

Related Questions