我有以下ST / ExtJS与Phonegap API的代码组合,但这是一个更通用的Javascript问题:
点击表单上的保存按钮后,我调用此方法:
onSavePush: function(button) {
var form = button.up('panel'),
//get the record
record = form.getRecord(),
//get the form values
values = form.getValues();
//if a new push
if(!record){
var newRecord = new EvaluateIt.model.SiteEvaluation(values);
Ext.getStore('SiteEvaluations').add(newRecord);
}
//existing push
else {
record.set(values);
}
form.hide();
// assemble record
//assemble_evaluation(record);
initialize_image_post(record, values);
// add file_name update to store here:
},
函数initialize_image_post()执行它所说的内容(设置API url并获取uri引用):
function initialize_image_post(record) {
var uri,
url;
// use new API with authorization token
url = EvaluateIt.config.protocol;
url += EvaluateIt.config.test;
url += EvaluateIt.config.domain;
// url += EvaluateIt.config.dev; // ev environment
// url += EvaluateIt.config.file_response; // needed for POST echo
url += EvaluateIt.config.apiViewNomination;
url += EvaluateIt.config.file_upload;
url += '?token=' + sessionStorage.sessionToken;
uri = record.data.imageUri; // local path to image
console.log('uri: ' + uri + 'url: ' + url);
post_image(uri, url);
}
然后在函数post_image()
中调用Phonegap文件传输API// Phonegap file transfer
function post_image(imageUri, url) {
var options = new FileUploadOptions(),
ft = new FileTransfer();
options.fileKey = 'userfile';
//options.fileName = imageUri.substr(imageUri.lastIndexOf('/') + 1);
options.mimeType = 'image/jpeg';
options.chunkedMode = false;
ft.upload(imageUri, encodeURI(url), post_success, post_error, options);
}
成功之后,我从服务器获取响应并获取file_name,这样我就可以在初始方法中将其写入本地数据存储
function post_success(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
alert(r.response);
var response = Ext.JSON.decode(r.response),
file_name = response.imageData.file_name;
alert(file_name);
// somehow get file_name back up to onSavePush method
}
问题是,要做到这一点,我需要将响应变量返回到我的onSavePush方法。我该怎么做呢?我假设我需要以某种方式设置一个回调链或一些这样的东西?古拉爵!
答案 0 :(得分:1)
我想您希望故意在onSavePush
方法中获得回复,对吗?然后,使用程序式编程,解决方案是在post_success
中定义onSavePush
回调并将其传递下去:
onSavePush: function(button) {
// bablabla
var post_success = function(r) {
// bablabla or "add file_name update to store here"
}
initialize_image_post(record, values, post_success);
}
function initialize_image_post(record, values, callback) {
// bablabla
post_image(uri, url, callback);
}
function post_image(imageUri, url, post_success) {
// bablabla
ft.upload(imageUri, encodeURI(url), post_success, post_error, options);
}
在理想世界中,您可以设计一个关注发布图像的类/单例,成功触发事件,因此您可以在onSavePush
中将一次性事件处理程序附加到其中。