I have an HTML page that references 2 javascript files x.js and y.js.
In y.js I request some data from a web service. When I receive the data I would like to call any methods that have registered an interest in the data. I added a RegisterCallback function to y.js and from x.js I call the function and pass it a function for the callback, which gets added to an array.
When the data is received from the web service a for loop calls all of the callback functions which have previously been registered.
This works and the callback function in x.js gets called. However a variable that was initialised in x.js is undefined when the callback function gets called.
It appears that the callback function that gets called in x.js is not the same x.js that was passed when the callback was registered. (If that makes sense)
In the example below the variable svgImage gets initialised but when the callback happens it is undefined.
x.js
var svgImage;
function InitialiseX() {
try {
this.svgImage = document.querySelector(this.svgView).getSVGDocument().querySelector(this.svgImageId);
RegisterDataReceivedCallback(ProcessReceivedData);
GetData()
}
catch (err) {
alert(err);
}}
function ProcessReceivedData(result) {
if (this.svgImage.querySelector("#" + parameterId)) {//Not Complete}}
y.js
var getParameterDataCallbacks = [];
function RegisterParameterDataReceivedCallback(callback){
getParameterDataCallbacks.push(callback);}
function GetParameterData(){
try {
$.ajax({
url: '/api/parametersdata',
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ UserLevel: "1000", IpAddress: deviceIpAddress }),
async: true,
processData: false,
cache: false,
success: function (data) {
for (key in getParameterDataCallbacks)
{
getParameterDataCallbacks[key](data);
}
},
error: function (error) {
}
});
}
catch (err) {
alert(err);
}}
If I call GetParameterData from x.js and pass the callback function instead of registering and storing it in the array it works fine.
How can I overcome this problem?