如果其他功能完成,我怎么才能执行功能?

时间:2015-03-20 14:17:22

标签: javascript

我正在使用chrome的文件系统API。

fileSystemInit = function(){
    //Browser specific
    window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;

    //request rights to save files to system.
    navigator.webkitPersistentStorage.requestQuota(1048*1048*8, function(grantedBytes) {
        //once approved (or previously approved):
        window.requestFileSystem(PERSISTENT, grantedBytes, onInitFs, errorHandler);
    }, function(e) {
    console.log('Error', e);
    });
};

//Once allowed save the file
onInitFs = function(fs) {
        data = 'some data'
        saveFile(fs, 'json.json', data)
        readFile(fs, 'json.json')
};

fileSystemInit请求permisisons,一旦提示,onInitFs运行保存和读取文件的函数。我希望从onInitFs之外运行saveFile和readFile,基本上在我的javascript中的任何地方。我需要访问fs,它只能在运行onInitFs后运行。什么是一个好方法呢?

这是saveFile和readFile:

saveFile = function(fs, filename, content){

    fs.root.getFile('json.json', {create: true}, function(fileEntry) {
        // Create a FileWriter object for our FileEntry.
        fileEntry.createWriter(function(fileWriter) {
            // Create a new Blob and write it to log.txt.
            var blob = new Blob([JSON.stringify(content)], {type: 'application/json'});
            fileWriter.write(blob);

            fileWriter.onwriteend = function(e) {
                console.log('Write completed.', e);
            };

            fileWriter.onerror = function(e) {
                console.log('Write failed: ', e);
            };
        }, errorHandler);

    }, errorHandler);
}

readFile = function(fs, filename){
        fs.root.getFile(filename, {}, function(fileEntry){

            fileEntry.file(function(file){
                var reader = new FileReader();
                reader.onloadend=function(e){
                    console.log('content:', this.result);
                };
                reader.readAsText(file);
            },errorHandler);

        },errorHandler);
};

errorHandler = function(e) {
  console.log('Error: ', e);
};

1 个答案:

答案 0 :(得分:1)

var globalFS;
onInitFs = function(fs) {
        globalFS = fs;
        data = 'some data'
        saveFile(fs, 'json.json', data)
        readFile(fs, 'json.json')
};

然后在其他地方:

saveFile = function(globalFS, filename, content){
    if(globalFS){
     //do whatever
    }
    else{
       alert("need permission to complete this action");
    }
}