将变量传递给函数callBack

时间:2013-03-22 14:00:51

标签: javascript cordova callback

如何获取fileDoesNotExist回调的变量,url和name:

window.checkIfFileExists = function(path, url, name) {
  return window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, (function(fileSystem) {
    return fileSystem.root.getFile(path, {
      create: false
    }, fileExists, fileDoesNotExist);
  }), getFSFail);
};

fileDoesNotExist = (fileEntry, url, name) ->
  downloadImage(url, name)

2 个答案:

答案 0 :(得分:2)

phoneGap的getFile功能有两个回调函数。你在这里犯的错误fileDoesNotExist是它应该调用两个函数,而不是引用一个变量。

以下内容可行:

window.checkIfFileExists = function(path, url, name) {
  return window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, (function(fileSystem) {
    return fileSystem.root.getFile(path, {
      create: false
    }, 
    function(e) {
      //this will be called in case of success
    },
    function(e) {
      //this will be called in case of failure
      //you can access path, url, name in here
    });
  }), getFSFail);
};

答案 1 :(得分:1)

您可以传入一个匿名函数,并将它们添加到回调调用中:

window.checkIfFileExists = function(path, url, name) {
  return window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, (function(fileSystem) {
    return fileSystem.root.getFile(path, {
      create: false
    }, fileExists, function(){
        //manually call and pass parameters
        fileDoesNotExist.call(this,path,url,name);
    });
  }), getFSFail);
};