我正在使用Phonegap和jQuery Mobile构建移动应用程序。
它是所有单.html
个文件,大约有10页data-role="page"
有一个Updates
页面应该从服务器获取更新(更新频率:每天)
当用户点击“更新”时,这就是策略:
我正在使用Cordova / Phonegap的File API,但我很难将对象从一个函数传递给另一个函数。因为,整个File API正在通过回调来完成。我期待,他们会将对象返回给我,以便我可以将它们传递给其他功能。由于这些回调,我觉得我已经失去了对执行流程的控制。它变得随意,非线性。
这是我完全断开的代码:
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);
}
答案 0 :(得分:1)
最简单的方法是将必要的变量保存为全局变量。我的意思是:
var savedFileEntry;
function gotFileEntry(fileEntry) {
console.log("Got File Entry");
savedFileEntry = fileEntry;
fileEntry.file(gotFile, fail);
}
然后你可以在任何地方使用它。
更新。您也可以尝试使用$ .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();
}