My goal is to change a value from an external object that is set with data from a json call.
I have an object in file 1(file1.js). this object get's its settings from an outside json file(setting.json). The object retrieves these settings with a json call.
file1.js
$(document).ready(function () {
let example;
$.getJSON( "setting.json", function(data) {
// create object based on settings
example = new ExampleObject(data);
}).fail(function(e) {
console.warn(e);
}).always(function() {
console.log("ExampleObject after json call: ");
console.log(example);
window.exampleObject = example; // is still undefined in other js file cause that runs before this finishes.
});
window.exampleObject = example; // is undefined cause json fetch finishes after setting this.
});
class ExampleObject{
constructor(settings){
this.width = settings.width;
this.height = settings.height;
}
setWidth(width){
this.width = width;
}
setHeight(height){
this.height = height;
}
}
setting.json
{
"width": 3,
"height": 4
}
This works and all but now i want to get this object from a thirdparty file(file2.js) so i can change some values.
I realise that the object is undefined because file2.js finishes before the json call in file1.js.
I would like file1.js to act independently so file1.js can still run if file2.js would not exist. So is there a way to wait for a jsoncall in another file so it sets the object correctly globally ?
if not. How would people go about this ?
file2.js
$(document).ready(function () {
// get object from global object
console.log(window.exampleObject);
// cant run this line since window.exampleObject is undefined.
window.exampleObject.setWidth(6);
console.log(window.exampleObject);
});
If things aren't clear please ask.
Note: A json call does not work with local file storage. You will need something lime xamp to run this yourself.