[英]How to pass Objects from one function to another
我正在使用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);
}
最簡單的方法是將必要的變量另存為全局變量。 我的意思是:
var savedFileEntry;
function gotFileEntry(fileEntry) {
console.log("Got File Entry");
savedFileEntry = fileEntry;
fileEntry.file(gotFile, fail);
}
然后,您可以在任何地方使用它。
UPDATE。 您也可以嘗試使用$ .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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.