modal--7.修改、增加(同步+异步)

本文介绍了一个用于编辑和提交用户需求的功能实现方案,包括前端页面布局、模态框设计及其实现逻辑,如添加和更新操作的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1      按钮

 

<button onclick="update(${items.id },'${items.value }')"
      data-toggle="modal" data-target="#myModal" type="button" class="btn btn-defaultbtn-xs update">
   <span class="glyphiconglyphicon-pencil"></span> 编辑
</button>

<a href="javascript:void(0)"id="add" class="btnbtn-default" style="float: right;"
   data-toggle="modal" data-target="#myModal">
   <span style="float:right;outline:none;">添加用户要求</span></a>
</h3>

2      模型框

 

<!-- 模态框(Modal)-->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content" style="border-radius:0">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title" id="myModalLabel">用户要求</h4>
            </div>
            <div class="modal-body">
               <form id="form1">
                  <input type="hidden" name="id" id="id"/>
                  <input type="hidden" name="type" id="type" value="4"/>
                  <input type="hidden" name="cnName" id="cnName" value="用户需求"/>
                  <input type="hidden" name="attr" id="attr" value="user_require"/>
                  <div class="input-group">
                       <span class="input-group-addon">用户要求</span>
                  <textarea cols="50" rows="5"
                        class="form-control" name="value" id="value" placeholder="200字以内" required>
                  </textarea>
                   </div><!-- /input-group -->
                    
               </form>
            </div>
            <div class="modal-footer">
                <div id="bu" style="float:right">
                   <button type="button" class="btnbtn-primary" id="save">提交保存</button>
                </div>
                
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>


 

3      增加

3.1  预加载

//点击添加用户要求
$("#add").click(function(){
   $("#bu").html('<button type="button" class="btn btn-primary"onclick="save()">提交保存</button>');
   $("#id").val("");
   $("#value").val("");
})

 

3.2  Js

function save() {
   var url = "<%=path %>/controller/param/addParam.do";
    $.ajax({
        type: "POST",
        dataType: "JSON",
        url: url,
        data: $('#form1').serialize(),
        success: function (data) {
           swal("保存成功!", "请继续操作!", "success");
           window.setTimeout(reload,700);
        },
        error: function(data) {
          alert("error:"+data.responseText);
         }
 
      });
}

3.3  Jscontroller

 

4      更新

4.1  预加载

function update(id, value) {
   $("#bu").html('<button type="button" class="btn btn-primary"onclick="queryupdate()">提交更新</button>');
   $("#id").val(id);
   $("#value").val(value);
}

 

4.2  Js

function queryupdate() {
   var url = "<%=path %>/controller/param/updateParam.do";
    $.ajax({
        type: "POST",
        dataType: "JSON",
        url: url,
        data: $('#form1').serialize(),
        success: function (data) {
           swal("更新成功!", "请继续操作!", "success");
           window.setTimeout(reload,700);
        },
        error: function(data) {
          alert("error:"+data.responseText);
         }
 
      });
}


 

 

 

 

 

 

 

 

 

------------------------ DataManager .js ------------------------ /** * 数据管理器类,负责与后端API通信并管理数据 */ class DataManager { constructor(baseUrl) { this.baseUrl = baseUrl; this.data = { bancais: [], dingdans: [], mupis: [], chanpins: [], kucuns: [], dingdan_chanpin_zujians: [], chanpin_zujians: [], zujians: [], caizhis: [], dingdan_chanpins: [], users: [] }; this.isSyncing = false; this.lastSync = null; } /** * 获取所有数据 * @returns {Promise<boolean>} 是否成功 */ async fetchAll() { try { const response = await fetch(`${this.baseUrl}/app/all`); if (!response.ok) throw new Error('Network response was not ok'); const result = await response.json(); if (result.status !== 200) throw new Error(result.text || 'API error'); // 更新本地数据 Object.keys(this.data).forEach(key => { if (result.data[key]) { this.data[key] = result.data[key]; } }); this.lastSync = new Date(); return true; } catch (error) { console.error('Fetch error:', error); return false; } } /** * 执行CRUD操作 * @param {string} operation - 'add', 'delete', 'update' * @param {string} entity - 实体名称(小写) * @param {Object} data - 要发送的数据 * @returns {Promise<Object>} 响应结果 */ async crudOperation(operation, entity, data) { try { const response = await fetch(`${this.baseUrl}/app/${operation}/${entity}`, { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(data) }); if (!response.ok) throw new Error('Network response was not ok'); const result = await response.json(); if (result.status !== 200) throw new Error(result.text || 'API error'); // 自动同步数据 this.syncData(); return result; } catch (error) { console.error('CRUD error:', error); throw error; } } /** * 自动同步数据(防止频繁请求) */ async syncData() { if (this.isSyncing) return; // 距离上次同步超过5秒才执行新同步 if (this.lastSync && new Date() - this.lastSync < 5000) { setTimeout(() => this.syncData(), 5000 - (new Date() - this.lastSync)); return; } this.isSyncing = true; try { await this.fetchAll(); } finally { this.isSyncing = false; } } /** * 添加实体 * @param {string} entity - 实体名称 * @param {Object} data - 实体数据 */ async addEntity(entity, data) { return this.crudOperation('add', entity, data); } /** * 更新实体 * @param {string} entity - 实体名称 * @param {Object} data - 实体数据(必须包含id) */ async updateEntity(entity, data) { return this.crudOperation('update', entity, data); } /** * 删除实体 * @param {string} entity - 实体名称 * @param {number} id - 实体ID */ async deleteEntity(entity, id) { return this.crudOperation('delete', entity, {id}); } } // 创建单例实例 const dataManager = new DataManager('http://your-backend-url.com'); // 初始化时获取所有数据 dataManager.fetchAll().then(() => { console.log('Initial data loaded'); }); // 导出数据对象,外部可以直接访问 data.bancais, data.dingdans 等 export const data = dataManager.data; // 导出操作方法 export const addEntity = dataManager.addEntity.bind(dataManager); export const updateEntity = dataManager.updateEntity.bind(dataManager); export const deleteEntity = dataManager.deleteEntity.bind(dataManager); export const fetchAll = dataManager.fetchAll.bind(dataManager); ------------------------ bancai.js ------------------------ $(document).ready(function() { const modal = new bootstrap.Modal('#bancaiModal'); let url={ bancis:"../bancai/all",//全部板材 caizhi:"../bancai/caizhis",//材质列表 mupi:"../bancai/mupis",//木皮列表 detete:"../bancai/delete/{id}",//板材删除 addbancai:"../bancai/add"//板材添加 } let currentMode = 'view'; // 'view', 'edit' 或 'add' let bancaiData = []; // 存储当前板材数据 let caizhiList = []; // 存储材质列表 let mupiList = []; // 存储木皮列表 // 初始化函数 async function initialize() { console.log("111111111") await fetchCaizhiOptions(); await fetchMupiOptions(); loadBancaiData(); } // 获取材质选项 function fetchCaizhiOptions() { console.log(url) return https(url.caizhi,null, function(data) { caizhiList = data; updateSelectOptions('#caizhiSelect', data); }); } // 获取木皮选项 function fetchMupiOptions() { return https(url.mupi,null, function(data) { for (var i in data) { mupiList[i]=data[i] mupiList[i].name=data[i].you?data[i].name+"(油漆)":data[i].name } // mupiList = data; updateSelectOptions('#mupi1Select', mupiList); updateSelectOptions('#mupi2Select', mupiList); } ); } // 更新下拉框选项 function updateSelectOptions(selector, data) { console.log(data) $(selector).empty(); data.forEach(item => { $(selector).append(`<option value="${item.id}">${item.name}</option>`); }); } // 加载板材数据 function loadBancaiData() { https(url.bancis,null, function(data) { bancaiData = data; renderBancaiTable(data); }); } // 渲染板材表格 function renderBancaiTable(data) { const $tbody = $('#bancaiTable tbody'); $tbody.empty(); console.log(data) data.forEach(bancai => { const caizhiName = bancai.caizhi?.name || '未知'; const mupi1Name = bancai.mupi1?.name || '未知'; const mupi2Name = bancai.mupi2?.name || '未知'; const row = ` <tr data-id="${bancai.id}"> <td>${bancai.id}</td> <td>${caizhiName}</td> <td>${mupi1Name} ${bancai.mupi1.you?'(油漆)':""}</td> <td>${mupi2Name} ${bancai.mupi2.you?'(油漆)':""}</td> <td>${bancai.houdu}</td> <td> <button class="btn btn-sm btn-info view-btn">查看</button> <button class="btn btn-sm btn-warning edit-btn">编辑</button> <button class="btn btn-sm btn-danger delete-btn">删除</button> </td> </tr> `; $tbody.append(row); }); // 绑定行按钮事件 bindTableEvents(); } // 绑定表格事件 function bindTableEvents() { // 查看按钮 $('.view-btn').click(function() { const id = $(this).closest('tr').data('id'); openModalForBancai(id, 'view'); }); // 编辑按钮 $('.edit-btn').click(function() { const id = $(this).closest('tr').data('id'); openModalForBancai(id, 'edit'); }); // 删除按钮 $('.delete-btn').click(function() { const id = $(this).closest('tr').data('id'); deleteBancai(id); }); } // 添加板材按钮点击事件 $('#addBancaiBtn').click(function() { // 清空表单 $('#bancaiForm')[0].reset(); $('#modalTitle').text('添加新板材'); currentMode = 'add'; // 启用表单 enableForm(true); modal.show(); }); // 打开弹窗显示板材数据 function openModalForBancai(id, mode) { const bancai = bancaiData.find(b => b.id === id); if (!bancai) return; currentMode = mode; // 填充表单 $('#bancaiId').val(bancai.id); $('#caizhiSelect').val(bancai.caizhi.id); $('#mupi1Select').val(bancai.mupi1.id); $('#mupi2Select').val(bancai.mupi2.id); $('#houdu').val(bancai.houdu); // 设置标题 $('#modalTitle').text(mode === 'view' ? '板材详情' : '编辑板材'); // 设置表单状态 enableForm(mode === 'edit'); modal.show(); } // 启用/禁用表单 function enableForm(enable) { $('#caizhiSelect').prop('disabled', !enable); $('#mupi1Select').prop('disabled', !enable); $('#mupi2Select').prop('disabled', !enable); $('#houdu').prop('disabled', !enable); $('#saveBtn').toggle(enable); } // 保存按钮点击事件 $('#saveBtn').click(function() { const formData = { id: $('#bancaiId').val(), caizhiId: parseInt($('#caizhiSelect').val()), mupi1Id: parseInt($('#mupi1Select').val()), mupi2Id: parseInt($('#mupi2Select').val()), houdu: parseFloat($('#houdu').val()) }; const method = currentMode === 'add' ? 'POST' : 'PUT'; const url = currentMode === 'add' ? '/api/bancai' : `/api/bancai/${formData.id}`; $.ajax({ url: url, method: method, contentType: 'application/json', data: JSON.stringify(formData), success: function() { loadBancaiData(); modal.hide(); }, error: function() { alert('操作失败,请重试'); } }); }); // 删除板材 function deleteBancai(id) { if (!confirm('确定要删除此板材吗?')) return; $.ajax({ url: `${url.detete}/${id}`, method: 'DELETE', success: function() { loadBancaiData(); } }); } // 初始化应用 initialize(); }); ------------------------ bancai.html ------------------------ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>板材数据管理</title> <!-- 引入 Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> <!-- 引入 jQuery --> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <div class="container mt-4"> <h1 class="mb-4">板材数据管理</h1> <button class="btn btn-primary" id="addBancaiBtn">添加新板材</button> <table class="table table-striped mt-3" id="bancaiTable"> <thead> <tr> <th>ID</th> <th>材质</th> <th>木皮1</th> <th>木皮2</th> <th>厚度</th> <th>操作</th> </tr> </thead> <tbody> <!-- 数据将通过 AJAX 加载 --> </tbody> </table> </div> <!-- 查看/编辑弹窗 --> <div class="modal fade" id="bancaiModal" tabindex="-1" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="modalTitle">板材详情</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <form id="bancaiForm"> <input type="hidden" id="bancaiId"> <div class="mb-3"> <label class="form-label">材质</label> <select class="form-select" id="caizhiSelect" name="caizhi"></select> </div> <div class="mb-3"> <label class="form-label">木皮1</label> <select class="form-select" id="mupi1Select" name="mupi1"></select> </div> <div class="mb-3"> <label class="form-label">木皮2</label> <select class="form-select" id="mupi2Select" name="mupi2"></select> </div> <div class="mb-3"> <label class="form-label">厚度</label> <input type="number" step="0.01" class="form-control" id="houdu" name="houdu"> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button> <button type="button" class="btn btn-primary" id="saveBtn">保存</button> </div> </div> </div> </div> <!-- 引入 Bootstrap JS --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script> <script src="../js/jsyilai.js"></script> <script> </script> </body> </html> 改造Bancai.js 从DataManager .js拿数据渲染html,再加入搜索框
06-14
DataManager.js:68 Fetch error: TypeError: Cannot read properties of undefined (reading 'baseUrl') at fetchAll (DataManager.js:52:44) at initialize (bancai.js:36:19) fetchAll @ DataManager.js:68 initialize @ bancai.js:36 await in initialize(异步) (匿名) @ bancai.js:232 e @ jquery-3.6.0.min.js:2 t @ jquery-3.6.0.min.js:2 setTimeout(异步) (匿名) @ jquery-3.6.0.min.js:2 c @ jquery-3.6.0.min.js:2 fireWith @ jquery-3.6.0.min.js:2 fire @ jquery-3.6.0.min.js:2 c @ jquery-3.6.0.min.js:2 fireWith @ jquery-3.6.0.min.js:2 ready @ jquery-3.6.0.min.js:2 B @ jquery-3.6.0.min.js:2 bancai.js:44 初始化失败: ReferenceError: data is not defined at updateOptions (bancai.js:51:9) at initialize (bancai.js:39:13) // bancai.js $(document).ready(function () { const modal = new bootstrap.Modal('#bancaiModal'); let currentMode = 'view'; let caizhiList = []; let mupiList = []; let currentSearchText = ''; // 从父窗口获取 DataManager let dataManager = null; // 等待父窗口的 DataManager 准备就绪 async function waitForDataManager() { return new Promise((resolve, reject) => { if (window.parent && window.parent.dataManager) { resolve(window.parent.dataManager); } else { reject(new Error('无法从父窗口获取 DataManager')); } }); } // 初始化函数 async function initialize() { try { dataManager = await waitForDataManager(); if (!dataManager || typeof dataManager.fetchAll !== 'function') { throw new Error('无效的 DataManager 实例'); } // 解构需要的方法和属性 const { data, addEntity, updateEntity, deleteEntity, fetchAll } = dataManager; // 确保数据已加载 await fetchAll(); // 更新材质和木皮选项 updateOptions(); // 渲染板材表格 refreshTable(); } catch (error) { console.error('初始化失败:', error); alert('系统初始化失败,请刷新页面或联系管理员'); } } // 更新材质和木皮选项 function updateOptions() { caizhiList = data.caizhis; updateSelectOptions('#caizhiSelect', caizhiList); mupiList = data.mupis.map(m => ({ ...m, name: m.you ? `${m.name}(油漆)` : m.name, })); updateSelectOptions('#mupi1Select', mupiList); updateSelectOptions('#mupi2Select', mupiList); } // 更新下拉框选项 function updateSelectOptions(selector, data) { $(selector).empty(); data.forEach(item => { $(selector).append(`<option value="${item.id}">${item.name}</option>`); }); } // 刷新表格 function refreshTable() { const filteredData = filterBancais(currentSearchText); renderBancaiTable(filteredData); } // 搜索过滤 function filterBancais(searchText) { if (!searchText) return data.bancais; return data.bancais.filter(bancai => { const caizhiName = bancai.caizhi?.name || ''; const mupi1Name = bancai.mupi1?.name || ''; const mupi2Name = bancai.mupi2?.name || ''; const houdu = bancai.houdu.toString(); return [ caizhiName.toLowerCase(), mupi1Name.toLowerCase(), mupi2Name.toLowerCase(), houdu.toLowerCase(), ].some(field => field.includes(searchText.toLowerCase())); }); } // 渲染表格 function renderBancaiTable(bancais) { const $tbody = $('#bancaiTable tbody'); $tbody.empty(); bancais.forEach(bancai => { const caizhiName = bancai.caizhi?.name || '未知'; const mupi1Name = bancai.mupi1?.name || '未知'; const mupi2Name = bancai.mupi2?.name || '未知'; const row = ` <tr data-id="${bancai.id}"> <td>${bancai.id}</td> <td>${caizhiName}</td> <td>${mupi1Name} ${bancai.mupi1?.you ? '(油漆)' : ''}</td> <td>${mupi2Name} ${bancai.mupi2?.you ? '(油漆)' : ''}</td> <td>${bancai.houdu}</td> <td> <button class="btn btn-sm btn-info view-btn">查看</button> <button class="btn btn-sm btn-warning edit-btn">编辑</button> <button class="btn btn-sm btn-danger delete-btn">删除</button> </td> </tr> `; $tbody.append(row); }); bindTableEvents(); } // 绑定表格事件 function bindTableEvents() { $('.view-btn').click(function () { const id = $(this).closest('tr').data('id'); openModalForBancai(id, 'view'); }); $('.edit-btn').click(function () { const id = $(this).closest('tr').data('id'); openModalForBancai(id, 'edit'); }); $('.delete-btn').click(function () { const id = $(this).closest('tr').data('id'); deleteBancai(id); }); } // 添加按钮事件 $('#addBancaiBtn').click(function () { $('#bancaiForm')[0].reset(); $('#modalTitle').text('添加新板材'); currentMode = 'add'; enableForm(true); updateOptions(); modal.show(); }); // 搜索按钮事件 $('#searchBtn').click(function () { currentSearchText = $('#searchInput').val(); refreshTable(); }); // 输入框实时搜索 $('#searchInput').on('input', function () { currentSearchText = $(this).val(); refreshTable(); }); // 打开弹窗显示板材数据 function openModalForBancai(id, mode) { const bancai = data.bancais.find(b => b.id === id); if (!bancai) return; currentMode = mode; $('#bancaiId').val(bancai.id); $('#caizhiSelect').val(bancai.caizhi.id); $('#mupi1Select').val(bancai.mupi1.id); $('#mupi2Select').val(bancai.mupi2.id); $('#houdu').val(bancai.houdu); $('#modalTitle').text(mode === 'view' ? '板材详情' : '编辑板材'); enableForm(mode === 'edit'); modal.show(); } // 启用/禁用表单 function enableForm(enable) { $('#caizhiSelect').prop('disabled', !enable); $('#mupi1Select').prop('disabled', !enable); $('#mupi2Select').prop('disabled', !enable); $('#houdu').prop('disabled', !enable); $('#saveBtn').toggle(enable); } // 保存按钮点击事件 $('#saveBtn').click(async function () { const formData = { id: $('#bancaiId').val(), caizhiId: parseInt($('#caizhiSelect').val()), mupi1Id: parseInt($('#mupi1Select').val()), mupi2Id: parseInt($('#mupi2Select').val()), houdu: parseFloat($('#houdu').val()), }; try { if (currentMode === 'add') { await addEntity('bancais', formData); } else { await updateEntity('bancais', formData); } refreshTable(); modal.hide(); } catch (error) { console.error('操作失败:', error); alert('操作失败,请重试'); } }); // 删除板材 async function deleteBancai(id) { if (!confirm('确定要删除此板材吗?')) return; try { await deleteEntity('bancais', id); refreshTable(); } catch (error) { console.error('删除失败:', error); alert('删除失败,请重试'); } } // 初始化应用 initialize(); });/** * 数据管理器类,负责与后端API通信并管理数据 */ class DataManager { constructor(baseUrl) { this.baseUrl = baseUrl; this.data = { bancais: [], dingdans: [], mupis: [], chanpins: [], kucuns: [], dingdan_chanpin_zujians: [], chanpin_zujians: [], zujians: [], caizhis: [], dingdan_chanpins: [], users: [] }; this.isSyncing = false; this.lastSync = null; // 回调注册表 this.callbacks = { // 全局回调 all: [], // 按实体类型分类的回调 bancais: [], dingdan: [], mupi: [], chanpin: [], kucun: [], dingdan_chanpin_zujian: [], chanpin_zujian: [], zujian: [], caizhi: [], dingdan_chanpin: [], user: [] // ...其他实体 }; } /** * 获取所有数据 * @returns {Promise<boolean>} 是否成功 */ async fetchAll() { try { const response = await fetch(`${this.baseUrl}/app/all`); if (!response.ok) throw new Error('Network response was not ok'); const result = await response.json(); if (result.status !== 200) throw new Error(result.text || 'API error'); // 更新本地数据 Object.keys(this.data).forEach(key => { if (result.data[key]) { this.data[key] = result.data[key]; } }); this.lastSync = new Date(); return true; } catch (error) { console.error('Fetch error:', error); return false; } } /** * 注册回调函数 * @param {string} entity - 实体类型(如'bancai')或'all'表示全局回调 * @param {Function} callback - 回调函数,参数为(operation, data) */ registerCallback(entity, callback) { if (!this.callbacks[entity]) { this.callbacks[entity] = []; } this.callbacks[entity].push(callback); } /** * 移除回调函数 * @param {string} entity - 实体类型 * @param {Function} callback - 要移除的回调函数 */ unregisterCallback(entity, callback) { if (!this.callbacks[entity]) return; const index = this.callbacks[entity].indexOf(callback); if (index !== -1) { this.callbacks[entity].splice(index, 1); } } /** * 触发回调 * @param {string} operation - 操作类型('add', 'update', 'delete') * @param {string} entity - 实体类型 * @param {Object} data - 相关数据 */ triggerCallbacks(operation, entity, data) { // 触发全局回调 this.callbacks.all.forEach(cb => cb(operation, entity, data)); // 触发特定实体回调 if (this.callbacks[entity]) { this.callbacks[entity].forEach(cb => cb(operation, data)); } } /** * 执行CRUD操作并触发回调 */ async crudOperation(operation, entity, data) { try { const response = await fetch(`${this.baseUrl}/app/${operation}/${entity}`, { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(data) }); if (!response.ok) throw new Error('Network response was not ok'); const result = await response.json(); if (result.status !== 200) throw new Error(result.text || 'API error'); // 触发操作成功的回调 this.triggerCallbacks(operation, entity, data); // 自动同步数据 this.syncData(); return result; } catch (error) { console.error('CRUD error:', error); // 触发操作失败的回调 this.triggerCallbacks(`${operation}_error`, entity, { data, error: error.message }); throw error; } } /** * 执行CRUD操作 * @param {string} operation - 'add', 'delete', 'update' * @param {string} entity - 实体名称(小写) * @param {Object} data - 要发送的数据 * @returns {Promise<Object>} 响应结果 */ async crudOperation(operation, entity, data) { try { const response = await fetch(`${this.baseUrl}/app/${operation}/${entity}`, { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(data) }); if (!response.ok) throw new Error('Network response was not ok'); const result = await response.json(); if (result.status !== 200) throw new Error(result.text || 'API error'); // 触发操作成功的回调 this.triggerCallbacks(operation, entity, data); // 自动同步数据 this.syncData(); return result; } catch (error) { console.error('CRUD error:', error); // 触发操作失败的回调 this.triggerCallbacks(`${operation}_error`, entity, { data, error: error.message }); throw error; } } /** * 自动同步数据(防止频繁请求) */ async syncData() { if (this.isSyncing) return; // 距离上次同步超过5秒才执行新同步 if (this.lastSync && new Date() - this.lastSync < 5000) { setTimeout(() => this.syncData(), 5000 - (new Date() - this.lastSync)); return; } this.isSyncing = true; try { await this.fetchAll(); } finally { this.isSyncing = false; } } /** * 添加实体 * @param {string} entity - 实体名称 * @param {Object} data - 实体数据 */ async addEntity(entity, data) { return this.crudOperation('add', entity, data); } /** * 更新实体 * @param {string} entity - 实体名称 * @param {Object} data - 实体数据(必须包含id) */ async updateEntity(entity, data) { return this.crudOperation('update', entity, data); } /** * 删除实体 * @param {string} entity - 实体名称 * @param {number} id - 实体ID */ async deleteEntity(entity, id) { return this.crudOperation('delete', entity, {id}); } } export { DataManager }; // 创建单例实例 const dataManager = new DataManager('http://127.0.0.1:8080/KuCun2'); // 初始化时获取所有数据 dataManager.fetchAll().then(() => { console.log('Initial data loaded'); }); // 导出数据对象,外部可以直接访问 data.bancais, data.dingdans 等 export const data = dataManager.data; // 导出操作方法 export const addEntity = dataManager.addEntity.bind(dataManager); export const updateEntity = dataManager.updateEntity.bind(dataManager); export const deleteEntity = dataManager.deleteEntity.bind(dataManager); export const fetchAll = dataManager.fetchAll.bind(dataManager);
06-15
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值