I am trying to set a variable value at an object (class) level from deep inside a few levels of nested anonymous javascript method calls. How do I do this?
Here is some code to explain what I am trying to do. Disclaimer: I am not that comfortable with the concept of closures in javascript, so I might be going along a wrong path here. Any suggestion about a succinct way to achieve what I want to do would be greatly appreciated.
// FileUtils object.
var FileUtils = function () {
// Member variables.
this.ConfRootDir = null;
};
// Method to get a file entry.
// successCallback has to be a method with a FileEntry object.
FileUtils.prototype.getFileEntry = function (fileName, successCallback) {
if (this.ConfRootDir == null) {
var thisObj = this;
// Request the root filesystem
// [** 1st callback, using anon method]
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
function (fileSystem) {
// Get the root directory of the file system.
var rootDir = fileSystem.root;
// Get the ConferenceToGo directory, or create if required.
// [** 2nd callback, using anon method]
rootDir.getDirectory("ConferenceToGo", { create: true, exclusive: false },
function (confDir) {
// Set values for future use
// [** Definitely wrong scoping. The class level variable
// can't be accessed using 'this'. What to do? **]
this.ConfRootDir = confDir;
// Now try getting the handle for the list file.
// [** 3rd callback, using anon method. Irrelevant at this point.]
this.ConfRootDir.getFile(fileName, { create: false },
successCallback, // Success callback [getFile]
function (error) {
logError("Unable to retrieve file: ", true, true, error);
}); // Failure callback [getFile]
}, // Success callback [getDirectory]
function (error) { logError("Unable to create new directory: ", true, true, error); }); // Failure callback [getDirectory]
}, // Success callback [requestFileSystem]
function (error) { logError("Problem reading file system: ", true, true, error); }
);
}
}
I know that the scoping (by using 'this') is all wrong in the above piece of code, but not sure how to get it right. I have seen a few answers about binding to context (like this one), but I am using anonymous methods so that makes it harder. Note: Although I show only one method in the prototype of FileUtils here, there a few more.
Those who are aware can probably recognize that I am using methods from the cordova (PhoneGap) library for cross-platform mobile dev in HTML5 and JS, but that is not really much relevant here.
… function() { function() { function() { …
// Set values for future use
// [** Definitely wrong scoping. The class level variable
// can't be accessed using 'this'. What to do? **]
this.ConfRootDir = confDir;
You already have preparated the answer: thisObj.ConfRootDir
. The thisObj
variable is available in the scope of the nested function, and still points to the this
keyword of the outer getFileEntry
function, i.e. to the FileUtils
instance.