I am playing with modules in Dojo 1.8 and I have a module defined like this:
define(["dojo/request/xhr", "dojo/json"],
function(xhr, JSON) {
var url = "server/provider.php";
return {
files: {},
getDirList: function() {
var self = this;
xhr(url).then(function(response) {
response = JSON.parse(response);
// would love to return the JSON for use here
}, function(err) {
console.error(err);
});
}
};
});
I have another module in which I’d love to call that method and then use it:
define(["dojo/dom",
"dojo/dom-construct",
"dojo/_base/array",
"afm/utils"
],
function(dom,domConst,array, utils) {
return {
produceHtml: function() {
var json = utils.getDirList(); //this returns undefined
var dirLength = json.length;
console.log(json);
for (var i = 0; i < json.length; i++) {
if(i % 2 === 0) {
domConst.place('<tr class="even"><td>' + json[i].name + '</td></tr>', 'output');
} else {
domConst.place('<tr><td>' + json[i].name + '</td></tr>', 'output');
}
}
}
};
});
Naturally I could just put the DOM creation code INTO the util module, but that is mixing view logic where it shouldn’t be. And it’s hideous if I want to reuse the util.getDirList method.
How can I use the JSON that gets returned by that method? Is anyone else doing this?
The result of the dojo/request/xhr call comes in asynchronously, so setting the response parameter is done only after returning.
What you want is return a Promise (read up here: http://dojotoolkit.org/documentation/tutorials/1.8/promises/ ).
But first of all: you can make the dojo/request parse the json data for you, as follows:
See here: http://dojotoolkit.org/reference-guide/1.8/dojo/request.html#dojo-request
Now combining this, your getDirList function could be just:
And then in your produceHtml you would do something like this: