1
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?

Espen
  • 3,607
  • 11
  • 48
  • 75
  • Welcome to the world of asynchronous programming with callbacks. Some degree of mental adjustment is required. – Jon Sep 17 '13 at 11:29

4 Answers4

2

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);
};
Björn
  • 29,019
  • 9
  • 65
  • 81
  • I see now why my thinking was wrong. Of course this is asynchronous. And of course the callback function cannot return anything through the getJSON function. This was the simplest of the answers. – Espen Sep 18 '13 at 10:54
1

$.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);
});
Andy
  • 61,948
  • 13
  • 68
  • 95
1

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.

Community
  • 1
  • 1
0

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);
});
}
BenM
  • 4,218
  • 2
  • 31
  • 58