синхронизовал подгрузку оборудования в менеджере оборудования со списком в котором они отображаются.
115 lines
4.7 KiB
TypeScript
115 lines
4.7 KiB
TypeScript
// VirtualList.ts или LazyLoadList.ts
|
||
import { _decorator, Component, Prefab, ScrollView, instantiate, UITransform, Node } from 'cc';
|
||
import { ItemButton } from '../ux/ItemButton';
|
||
import { apiSensors } from '../stores/apiSensors';
|
||
import { EquipmentManager } from '../stores/EquipmentManager';
|
||
const { ccclass, property } = _decorator;
|
||
|
||
@ccclass("LazyLoadList")
|
||
export class LazyLoadList extends Component {
|
||
|
||
@property(Prefab)
|
||
public itemPrefab: Prefab = null!;
|
||
|
||
@property(ScrollView)
|
||
public scrollView: ScrollView = null!;
|
||
|
||
@property
|
||
public spacing: number = 10;
|
||
|
||
private _data: apiSensors[] = [];
|
||
private _totalCount: number = 0;
|
||
private _loadedCount: number = 0;
|
||
private _itemHeight: number = 0;
|
||
private _content: Node = null!;
|
||
private _contentUI: UITransform = null!;
|
||
|
||
onLoad() {
|
||
if (!this.scrollView.content) {
|
||
console.error("ScrollView.content равен null!");
|
||
return;
|
||
}
|
||
this._content = this.scrollView.content;
|
||
this._contentUI = this._content.getComponent(UITransform)!;
|
||
if (!this._contentUI) {
|
||
console.error("Узел content не имеет компонента UITransform!");
|
||
return;
|
||
}
|
||
|
||
// Определяем высоту элемента через префаб
|
||
const tempNode: Node = instantiate(this.itemPrefab);
|
||
const tempUI = tempNode.getComponent(UITransform);
|
||
if (!tempUI) {
|
||
console.error("В префабе отсутствует компонент UITransform!");
|
||
tempNode.destroy();
|
||
return;
|
||
}
|
||
this._itemHeight = tempUI.height;
|
||
tempNode.destroy();
|
||
|
||
// Пытаемся подписаться на событие обновления данных из EquipmentManager
|
||
this.waitForEquipmentManager();
|
||
}
|
||
|
||
// Рекурсивно ожидаем появления EquipmentManager.instance
|
||
private waitForEquipmentManager() {
|
||
if (!EquipmentManager.instance) {
|
||
console.warn("EquipmentManager.instance не найден, повторная попытка...");
|
||
this.scheduleOnce(() => { this.waitForEquipmentManager(); }, 0.1);
|
||
return;
|
||
}
|
||
// Как только EquipmentManager.instance доступен, подписываемся на событие
|
||
EquipmentManager.instance.node.on('data-updated', this.onDataUpdated, this);
|
||
// Если данные уже были загружены до подписки, можно сразу инициировать обновление списка:
|
||
this.onDataUpdated();
|
||
}
|
||
|
||
// Обработчик события, когда данные обновлены
|
||
private async onDataUpdated() {
|
||
if (!EquipmentManager.instance) return;
|
||
// Получаем актуальные данные через метод, который использует мьютекс
|
||
this._data = (await EquipmentManager.instance.getDataList()).map(item => ({ ...item }));
|
||
this._totalCount = this._data.length;
|
||
// Можно очистить список, если требуется полное обновление
|
||
this._loadedCount = 0;
|
||
this._content.removeAllChildren();
|
||
this.loadNextBatch(20);
|
||
}
|
||
|
||
/**
|
||
* Загружает следующую партию элементов (batchSize элементов).
|
||
*/
|
||
loadNextBatch(batchSize: number) {
|
||
if (this._loadedCount >= this._totalCount) return;
|
||
|
||
const startIndex = this._loadedCount;
|
||
const endIndex = Math.min(this._loadedCount + batchSize, this._totalCount);
|
||
for (let i = startIndex; i < endIndex; i++) {
|
||
const item: Node = instantiate(this.itemPrefab);
|
||
const posY = - (this._itemHeight * (0.5 + i) + this.spacing * (i + 1));
|
||
item.setPosition(0, posY, 0);
|
||
this._content.addChild(item);
|
||
|
||
const itemButton = item.getComponent(ItemButton);
|
||
if (itemButton) {
|
||
itemButton.initialize(this._data[i]);
|
||
itemButton.itemIndex = i;
|
||
}
|
||
}
|
||
this._loadedCount = endIndex;
|
||
this._contentUI.height = this._loadedCount * (this._itemHeight + this.spacing) + this.spacing;
|
||
}
|
||
|
||
update(dt: number) {
|
||
if (!this.scrollView.content) return;
|
||
const threshold = 50;
|
||
const visibleHeight = this.scrollView.node.getComponent(UITransform)!.height;
|
||
const offset = Math.abs(this.scrollView.content.position.y);
|
||
if (offset >= (this._contentUI.height - visibleHeight - threshold)) {
|
||
if (this._loadedCount < this._totalCount) {
|
||
this.loadNextBatch(20);
|
||
}
|
||
}
|
||
}
|
||
}
|