使用ajax加载的jQuery Dialog使PLUpload运行良好

时间:2011-08-29 22:47:00

标签: jquery jquery-ui jquery-ui-dialog plupload

他是我的自定义jQuery代码:

/* Files */
$(document).ready(function() {

    // -----------------------------------------------------
    // Define Variables
    // -----------------------------------------------------
    var $filesTab = $("#files");
    var $filesList = $("#files-list");
    var $foldersList = $("#file-folders");
    var $uploadBtn = $("#upload-file");

    var objectData = {
        "object" : $filesTab.data("object"),
        "object_id" : $filesTab.data("object-id")
    };

    // -----------------------------------------------------
    // Load data
    // -----------------------------------------------------
    var filesDataTable = $filesList.dataTable({
        "oLanguage" : {
                'sSearch': "Search Files:"
        },
        "iDisplayLength" : 25
    });

    $foldersList.bind("load", function() {
        // Load Folders
        $foldersList.load("/global-ajax/files/get-folders/", objectData);
    }); $foldersList.trigger("load");




    // -----------------------------------------------------
    // Events
    // -----------------------------------------------------
    $uploadBtn.bind("click", function() {
        debug.log("Clicked upload file btn");           
        var uploadFileOptions = objectData;

        // Get data and create modal
        $.get("/global-ajax/files/get-upload-modal/", uploadFileOptions, function(response) {
            debug.log("Ajax returned");
            $(response).dialog({
                draggable: false,
                modal: true,
                resizable: false,
                stack: false,
                title: "Upload a File",
                width: '50%',
                buttons: {
                    'Upload': function() {
                        // submit, do callback
                        var $form = $(this);
                        var serialized_form_data = decodeURIComponent($form.serialize());
                        // console.log("Serialized Form Data: " + serialized_form_data);
                        $form.addClass("loading").find("input, select, textarea").attr("disabled", true);
                        $.post("/global-ajax/files/upload-file/", serialized_form_data, function(json) {

                            $form.removeClass("loading").find("input, select, textarea").attr("disabled", false);
                        }, "json");
                    },
                    'Cancel': function() {
                        $(this).dialog("close");
                    }
                },
                open: function(event, ui) {

                    var uploader = new plupload.Uploader({
                        runtimes : 'gears,html5,flash,silverlight,browserplus',
                        browse_button : 'pickfiles',
                        container : 'file-upload',
                        max_file_size : '10mb',
                        url : 'upload.php',
                        flash_swf_url : '/app/javascript/plupload/plupload.flash.swf',
                        multi_selection : false
                    });


                    uploader.bind('Init', function(up, params) {
                        $('#filelist').html("<div>Current runtime: " + params.runtime + "</div>");
                    });

                    $('#uploadfiles').live("click", function(e) {
                        uploader.start();
                        e.preventDefault();
                    });

                    uploader.bind('FilesAdded', function(up, files) {
                        $.each(files, function(i, file) {
                            $('#filelist').append(
                                '<div id="' + file.id + '">' +
                                file.name + ' (' + plupload.formatSize(file.size) + ') <b></b>' +
                            '</div>');
                        });

                        up.refresh(); // Reposition Flash/Silverlight
                    });

                    uploader.bind('UploadProgress', function(up, file) {
                        $('#' + file.id + " b").html(file.percent + "%");
                    });

                    uploader.bind('Error', function(up, err) {
                        $('#filelist').append("<div>Error: " + err.code +
                            ", Message: " + err.message +
                            (err.file ? ", File: " + err.file.name : "") +
                            "</div>"
                        );

                        up.refresh(); // Reposition Flash/Silverlight
                    });

                    uploader.bind('FileUploaded', function(up, file) {
                        $('#' + file.id + " b").html("100%");
                    });             

                    uploader.init();
                }
            });


        });

    });
});

HTML按钮代码:

<div class="g3" id="files-sidebar">
    <a class="btn green icon big i_cloud_upload" id="upload-file" href="javascript:;">Upload File</a>
    <h4>Folders</h4>
    <div id="file-folders"><ul>
    <li title="Drag and drop files to add to folder" class="i_folder selected">CAD Files (3)</li>
    <li class="i_folder">Estimates (1)</li>
    <li class="i_folder">Photos (24)</li>
    <li class="i_folder">Uncategorized (11)</li>
</ul>
<p>You can create a custom folder when uploading or editing a file.</p>
</div>
    </div>

HTML Ajax已加载到对话框中:

<form id='' method='POST' enctype='multipart/form-data' action=''  class="">
<input type="hidden" name="key" value="3b53c6cd33f342246b5cbd59440dac18" />
    <fieldset>

            <section id="field_description" class="field">
                <label for="description" id="">Description: </label>
                <div>
                    <textarea id="description" name="description" class="textarea maxwidth-400 "   ></textarea>
                    <span></span>
                </div>

            </section>

            <section id="field_revision_no" class="checkbox-field field">
                <label for="revision_no" id="">Upload as New File</label>
                <div>           
                    <input type="radio" id="revision_no" name="revision"  value="no" class="radio "  CHECKED="CHECKED"   />


                </div>
            </section>

            <section id="field_revision_yes" class="checkbox-field field">
                <label for="revision_yes" id="">Upload as Revision</label>
                <div>           
                    <input type="radio" id="revision_yes" name="revision"  value="yes" class="radio "   />


                </div>
            </section>
                <div id="file-upload">
            <div id="filelist"></div>
            <a id="pickfiles" href="#">[Select files]</a>
        </div>
    </fieldset>
</form>

这里有一些与我的问题无关的事情。那么,为了让您对我正在尝试做的事情有一个基本的了解......我正在开发一个需要文件上传功能的管理系统。每个项目都使用jQuery UI选项卡。有一个文件选项卡,其中包含上传文件的列表和带有上传文件按钮的侧栏。该按钮在代码中被引用为$ uploadBtn。

页面上加载了所有必需的jQuery和PLUpload文件。

我的困难在于我想使用jQuery UI Dialog小部件从ajax文件加载我的上传表单。我每次单击上传按钮时都会使用该部件,但PLUpload仅在第一次打开上载对话框时正确初始化。我已经尝试在Dialog的beforeClose处理程序中销毁该实例,但这似乎不起作用。

如何每次打开上传对话框而不是第一次正确初始化PLUpload!?谢谢!

Screenshot

2 个答案:

答案 0 :(得分:1)

我已经使用.remove()的以下用法来元素化了之前启动的jQuery UI对话框,并发现它取得了很大的成功。

'Close':function()
{
  $(this).dialog('close');
  $(this).remove();
}

答案 1 :(得分:0)

$.extend($.ui.dialog.overlay, { create: function(dialog){
  if (this.instances.length === 0) {
    // prevent use of anchors and inputs
    // we use a setTimeout in case the overlay is created from an
    // event that we're going to be cancelling (see #2804)
    setTimeout(function() {
      // handle $(el).dialog().dialog('close') (see #4065)
      if ($.ui.dialog.overlay.instances.length) {
        $(document).bind($.ui.dialog.overlay.events, function(event) {
          var parentDialog = $(event.target).parents('.ui-dialog');
          if (parentDialog.length > 0) {
            var parentDialogZIndex = parentDialog.css('zIndex') || 0;
            return parentDialogZIndex > $.ui.dialog.overlay.maxZ;
          }

          var aboveOverlay = false;
          $(event.target).parents().each(function() {
            var currentZ = $(this).css('zIndex') || 0;
            if (currentZ > $.ui.dialog.overlay.maxZ) {
              aboveOverlay = true;
              return;
            }
          });

          return aboveOverlay;
        });
      }
    }, 1);

    // allow closing by pressing the escape key
    $(document).bind('keydown.dialog-overlay', function(event) {
      (dialog.options.closeOnEscape && event.keyCode
       && event.keyCode == $.ui.keyCode.ESCAPE && dialog.close(event));
    });

    // handle window resize
    $(window).bind('resize.dialog-overlay', $.ui.dialog.overlay.resize);
  }

  var $el = $('<div></div>').appendTo(document.body)
  .addClass('ui-widget-overlay').css({
    width: this.width(),
    height: this.height()
  });

  (dialog.options.stackfix && $.fn.stackfix && $el.stackfix());

  this.instances.push($el);
  return $el;
}});