我正在使用 Javascript 编写一个应用程序,该应用程序将与 Phonegap 一起使用来制作 Android 应用程序。我正在使用 Phonegap File API 来读取目录和文件。相关代码如下所示:
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, fail);
}
function onFileSystemSuccess(fileSystem) {
fileSystem.root.getDirectory("/sdcard", {create: false, exclusive: false}, getDirSuccess, fail);
}
function getDirSuccess(dirEntry) {
// Get a directory reader
var directoryReader = dirEntry.createReader();
// Get a list of all the entries in the directory
directoryReader.readEntries(readerSuccess,fail);
}
var numDirs = 0;
var numFiles = 0;
function readerSuccess(entries) {
var i;
for (i=0; i<entries.length; i++)
{
if(entries[i].isFile === true)
{
numFiles++;
entries[i].file(fileSuccess,fail);
}
else if (entries[i].isDirectory === true)
{
numDirs++;
getDirSuccess(entries[i]);
}
}
}
所以到目前为止,该程序运行良好。读取器将读取 /sdcard 目录的内容。如果遇到文件,它将调用 fileSuccess (为了简洁起见,我在代码中排除了该文件),如果遇到另一个目录,它将再次调用 getDirSuccess。我的问题是:我如何知道整个 /sdcard 目录何时被读取?我想不出一种在不多次遍历 /sdcard 目录的情况下完成此操作的好方法。任何想法表示赞赏,并预先感谢您!
+1是一个好问题,因为无论如何我自己都必须这样做。我会使用旧的 setTimeout 技巧。一旦取消不再发生,您就知道您已经完成并可以触发您的事件,但只需确保它只触发一次。
这就是我的意思,我将变量命名为 long 只是为了更具可读性(不是我的风格)......
// create timeout var outside your "readerSuccess" function scope
var readerTimeout = null, millisecondsBetweenReadSuccess = 100;
function readerSuccess(entries) {
var i = 0, len = entries.length;
for (; i < len; i++) {
if (entries[i].isFile) {
numFiles++;
entries[i].file(fileSuccess,fail);
} else if (entries[i].isDirectory) {
numDirs++;
getDirSuccess(entries[i]);
}
if (readerTimeout) {
window.clearTimeout(readerTimeout);
}
}
if (readerTimeout) {
window.clearTimeout(readerTimeout);
}
readerTimeout = window.setTimeout(weAreDone, millisecondsBetweenReadSuccess);
}
// additional event to call when totally done
function weAreDone() {
// do something
}
因此,其中的逻辑是,当您阅读内容时,您会不断取消调用“weAreDone”函数。不确定这是否是最好的方法或更有效,但考虑到适当的“millisecondsBetweenReadSuccess”,它不会导致超过一个循环。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)