You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vanilla JavaScript模块项目:如何从子文件向父文件传递数组

解决方案:Vanilla JS模块间同步更新后的数组副本(无setInterval)

针对你需要在Vanilla JavaScript模块中,让父文件(index.js)获取子文件(main.js)频繁更新的数组副本且不使用轮询的需求,以下是两种实用实现方案:

方案一:发布订阅模式(观察者模式)

这种模式让父模块主动订阅数组更新事件,子模块在数组变化时主动推送副本,灵活性高,适用于任何JS环境。

main.js(子文件)

// 维护子模块内部的数组
let internalArray = [];
// 存储订阅数组更新的回调函数
const updateSubscribers = [];

// 对外暴露订阅方法,父模块通过这个方法注册回调
export function subscribeArrayUpdate(callback) {
  updateSubscribers.push(callback);
  // 订阅时立即返回当前数组的副本
  callback([...internalArray]);
}

// 内部更新数组的方法,更新完成后通知所有订阅者
function updateInternalArray(newData) {
  // 替换内部数组(可根据实际需求调整为push/unshift等更新逻辑)
  internalArray = [...newData];
  // 给每个订阅者传递数组副本,避免外部修改影响内部数据
  updateSubscribers.forEach(cb => cb([...internalArray]));
}

// 示例:模拟数组频繁更新的场景
setTimeout(() => updateInternalArray([1, 2, 3]), 1000);
setTimeout(() => updateInternalArray([4, 5, 6]), 2000);
setTimeout(() => updateInternalArray([7, 8, 9]), 3000);

index.js(父文件)

import { subscribeArrayUpdate } from './main.js';

// 订阅数组更新,每次数组变化都会收到最新副本
subscribeArrayUpdate((latestArrayCopy) => {
  console.log('获取到更新后的数组副本:', latestArrayCopy);
  // 在这里处理副本,比如赋值给父模块的变量
});

方案二:自定义DOM事件(浏览器环境专属)

如果你的项目运行在浏览器中,可以利用浏览器的自定义事件API来传递更新后的数组副本:

main.js(子文件)

let internalArray = [];

// 对外暴露获取数组副本的只读访问器
export const sharedArray = {
  get value() {
    // 返回副本,避免外部修改内部数组
    return [...internalArray];
  }
};

// 对外暴露更新数组的方法,更新后派发自定义事件
export function updateArray(newItems) {
  internalArray = [...newItems];
  // 向window派发自定义事件,携带数组副本
  window.dispatchEvent(new CustomEvent('arrayUpdated', {
    detail: [...internalArray]
  }));
}

// 示例:模拟数组更新
setTimeout(() => updateArray([10, 11, 12]), 1000);

index.js(父文件)

import { sharedArray } from './main.js';

// 初始获取数组副本
console.log('初始数组副本:', sharedArray.value);

// 监听自定义事件,获取更新后的副本
window.addEventListener('arrayUpdated', (event) => {
  const latestArrayCopy = event.detail;
  console.log('通过事件收到的数组副本:', latestArrayCopy);
});

注意事项

  • 上述方案均使用[...array]实现浅克隆,如果数组包含嵌套对象/数组,需要使用深克隆(比如JSON.parse(JSON.stringify(array))或自定义深克隆函数)。
  • 所有传递给父模块的都是数组副本,确保父模块的操作不会影响子模块的内部数组状态。

内容的提问来源于stack exchange,提问作者Latha G M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 17:15:01