萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

EasyUI 實現第二層彈出對話框:模組化擴展元件

場景

主頁面彈出對話框(第一層),對話框內再彈出第二層對話框(如:選擇器、詳情頁)。需確保兩層互不干擾、獨立關閉、可傳遞回調。

擴展元件:$.modalDialogTwo

$.modalDialogTwo = function(options) {
    // 防止重複彈出
    if ($.modalDialogTwo.handler == undefined) {
        var opts = $.extend({
            title: '',
            width: 840,
            height: 680,
            modal: true,
            onClose: function() {
                $.modalDialogTwo.handler = undefined; // 釋放句柄
                $(this).dialog('destroy');            // 銷毀 DOM
            },
            onOpen: function() {
                // 可選:顯示進度條
                // parent.$.messager.progress({ title: '提示', text: '數據加載中...' });
            }
        }, options);
        
        opts.modal = true; // 強制模態
        // 建立 div 並初始化 dialog,回傳 handler
        return $.modalDialogTwo.handler = $('<div/>').dialog(opts);
    }
};

使用方式

第一層對話框(標準 EasyUI dialog)

// 父頁面
var dlg = $('
').dialog({ href: 'formPage.jsp', title: '新增記錄', width: 800, height: 600, modal: true });

第二層對話框(在第一層頁面內調用)

// formPage.jsp 內的 JS
function openSelector() {
    $.modalDialogTwo({
        href: 'selectorPage.jsp',
        title: '選擇器',
        width: 600,
        height: 400,
        onClose: function() {
            // 第二層關閉時的回調,可刷新第一層某些欄位
            // 例如:$('#someField').val($.modalDialogTwo.selectedValue);
        }
    });
}

關鍵設計點

設計點實現方式
單例模式$.modalDialogTwo.handler 靜態屬性持有實例,防止重複彈出
自動銷毀onClose 中 dialog('destroy') 釋放記憶體,避免 DOM 殘留
強制模態opts.modal = true 覆蓋傳入參數,確保層級遮罩
跨層通訊約定 $.modalDialogTwo.xxx 掛載共享資料/回調函數
父頁面訪問parent.$.modalDialogTwo.handler 可在父頁面操作第二層

進階:Promise 化回調

$.modalDialogTwo = function(options) {
    return new Promise((resolve, reject) => {
        if ($.modalDialogTwo.handler) return reject('已有實例');
        var opts = $.extend({ ... }, options);
        opts.onClose = function() {
            $.modalDialogTwo.handler = undefined;
            $(this).dialog('destroy');
            resolve($.modalDialogTwo.result); // 關閉時 resolve 結果
        };
        opts.onSave = function(data) { // 約定內部調用
            $.modalDialogTwo.result = data;
        };
        $.modalDialogTwo.handler = $('
').dialog(opts); }); }; // 使用 async function doSelect() { try { var result = await $.modalDialogTwo({ href: 'selector.jsp' }); console.log('用戶選擇:', result); } catch (e) { console.log('取消或錯誤'); } }

結語

多層對話框是企業級後台系統常見需求。封裝 $.modalDialogTwo 統一管理實例生命週期、模態層級、跨層通訊,能避免「遮罩穿透、實例殘留、回調地獄」等常見問題。現代專案建議改用 Vue/React Portal + 狀態管理實現同樣邏輯。

copyright © 萬盛學電腦網 all rights reserved