掌握javascript回调 - 未定义的回调数据

时间:2014-03-10 13:13:53

标签: javascript jquery ajax callback

我的javascript技能有限,我遇到了一系列函数的结构问题,我认为需要回调。我一直在阅读一些帖子和教程,但它并没有坚持......但是......

在我的页面上,我有一个包含图像的弹出模式。如果用户单击编辑按钮,则在鸟舍中进行编辑。完成后,图像属性将保存到数据库中,然后模态框中的图像 - 以及基础表单 - 应该使用编辑后的图像进行更新。

我的一系列事件以模态开头开始:

 $('#editImageLink2').click(function(event) {

    aviaryOnClick('image2', $(this).data('mode'), function(image) {

      #do final bits here

    });
});

如果用户点击编辑按钮,则弹出模态,然后下一个功能启动编辑器:

function aviaryOnClick(source, mode) {

editedImage = doAviary(source);

if (editedImage) {

    return true;

} else {
    return false;
}

}

所以 - 鸟舍按预期弹出。然后当用户保存编辑过的图像时,我开始遇到麻烦:

doAviary函数如下所示:

function doAviary(source) {

console.log("hit doAviary", source);

var featherEditor = new Aviary.Feather({
    apiKey: 'XXXXXXXX',
    apiVersion: 3,
    theme: 'dark', 
    tools: 'all',
    displayImageSize: true,
    maxSize: 1200,
    onSave: function(imageID, newURL) {

        //replace image in modal preview
        var img = document.getElementById(imageID);
        img.src = newURL;
        if (newURL != undefined) {

            storeImage(newURL, updateFormImage(imageData));

            featherEditor.close();

            return true;
        }

    },
    onError: function(errorObj) {
        alert(errorObj.message);

        return false;
    }
});

return featherEditor.launch({
    image: source,
    url: $('#' + source).attr('src')

});


 }

所以我试图在onSave事件中运行storeImage,然后应该使用图像数据对更新图像进行回调。

我的storeImage功能:

function storeImage(newURL, imageData) {

var options = new Object();
options.aviaryURL = newURL;
options.mode = mode;
options.dbID = ($('#dbID').val()) ? $('#dbID').val() : null;

//console.log("store image options object:", options);

jQuery.ajax({
    url: '/filemanager/aviary',
    type: 'POST',
    dataType: 'json',
    data: options,
    complete: function(xhr, textStatus) {
        //called when complete
    },
    success: function(data, textStatus, xhr) {
        //called when successful
        console.log("finished store image", data);
        $.cookie('asset_filename', data.image.filename);
        $.cookie('asset_id', data.image.id);

        imageData(data);

    },
    error: function(xhr, textStatus, errorThrown) {
        //called when there is an error
        imageData(false);
    }
});

因此,如果保存图像,则应将数据传递回回调。如果失败则为假

然后在更新图像功能

function updateFormImage(data) {

if (data.result == 'success') {

    image = data.image;

    #simple updates of elements in page


}

}

我目前的问题是,在保存时我收到错误imageData is not defined - 我不知道为什么会这样 - 如果它在将数据传回回调之前等待ajax完成它应该存在。

为什么会发生此错误?

有什么更好的方法可以重构此代码并正确使用回调。

我最初对第一个函数进行了回调,但得到了一个未定义的错误回调函数

混淆。

谢谢

1 个答案:

答案 0 :(得分:1)

imageData未定义到doAviary。

此外,updateFormImage应返回一些内容(imageData)。