claws
claws

Reputation: 54100

How to pass Objects from one function to another

I'm building a mobile app using Phonegap and jQuery Mobile. It's all single .html file with around 10 pages data-role="page" There is a Updates page which should fetch the updates from the server (update frequency: everyday)

When user clicks "Updates" this is the strategy:

enter image description here

I'm using File API of Cordova/Phonegap but I'm having hardtime passing objects from one function to other. Because, this entire File API is working through callbacks. I was expecting, they'll return the objects to me so that I can pass them to other functions. Because of these call backs I feel like I've lost control over the flow of execution. It became haphazard, non-linear.

This is my completely disconnected code:

function getUpdate(){
    alert("inside getUpdate");
    jQuery.ajax({
        url: 'http://example.com/updates.jsonp',
        dataType: 'jsonp',
        success: function(jsonobj){
            var text = '';
            var update = jsonobj[0];
            // I need to pass this `jsonobj` to other functions
            alert('Node nid: ' + update.nid );
            startFileReadingProcess();
        }


    });
}

function startFileReadingProcess() {
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}

function gotFS(fileSystem) {
    fileSystem.root.getFile("updates.json", {create: true, exclusive: false}, gotFileEntry, fail);
}

function gotFileEntry(fileEntry) {
    console.log("Got File Entry");          
    fileEntry.file(gotFile, fail); //<-- I need to pass this fileEntry to fileWriter
}

function gotFile(file){
    console.log("Got File Pointer Success");        
    readAsText(file);
}

function readAsText(file) {
    var reader = new FileReader();
    reader.onloadend = function(evt) {
        console.log("Read Success: Read as text");
        console.log(evt.target.result);
    };
    reader.readAsText(file);
    checkContentsEmpty(reader.result, file)
}

function checkContentsEmpty(filecontents, file){
    if(filecontents){
        alert(filecontents);
        var jsonobj = JSON.parse(filecontents);
    }
    else{
        alert("filecontents=null => File is Empty");
    }
}

// This function is duplicate. I've already got gotFileEntry for fileReader. How to avoid this?
function gotFileEntry(fileEntry) {
    //I need the fileEntry object, got in above function
    fileEntry.createWriter(gotFileWriter, fail);
}

function gotFileWriter(writer) {
// I need json update got from the server in this function
writer.onwrite = function(evt) {
    console.log("write success");
};
writer.write( "Some sample text" );
}

function fail(error) {
    alert("Failed to retrieve file: " + error.code);
}

Upvotes: 0

Views: 564

Answers (1)

Regent
Regent

Reputation: 5178

The easiest way to do it is to save necessary variables as global variables. I mean:

var savedFileEntry;

function gotFileEntry(fileEntry) {
    console.log("Got File Entry");
    savedFileEntry = fileEntry;
    fileEntry.file(gotFile, fail);
}

Then you can use it anywhere.

UPDATE. You can also try to use $.Deferred

http://api.jquery.com/category/deferred-object/

function gotFileEntry(fileEntry) {
    console.log("Got File Entry");          
    var promise = getFile(fileEntry);
    promise.done(function(result) {
        if (result) {
            fileEntry.createWriter(gotFileWriter, fail);
        }
    });
}

function getFile(fileEntry) {
    var deferred = $.Deferred();
    fileEntry.file(function(file) {
        gotFile(file);
        deferred.resolve(true);
    },
    function(error) {
        fail(error);
        deferred.resolve(false);
    });
    return deferred.promise();
}

Upvotes: 1

Related Questions