我有一个virtualList
模板,我想重复使用不同的数据(virtList.items
)。如何将其抽象为数据,即使其更像模块?
virtList.js:
// imports {..};
const virtList = {};
Template.virtualList.onCreated(() => {
virtList.items = getItems();
virtList.itemsAmount = virtList.items.length;
virtList.itemHeight = 40;
Session.set("startIndex", 0);
Session.set("endIndex", 0);
});
Template.virtualList.onRendered(() => {
virtList.containerHeight = $('.list__container').height();
virtList.scrollerHeight = virtList.itemsAmount * virtList.itemHeight;
Session.set("endIndex", virtList.containerHeight / virtList.itemHeight);
$('.list__scroller').css({
'height': virtList.scrollerHeight
});
});
Template.virtualList.helpers({
items: () => visibleItems(Session.get("startIndex"), Session.get("endIndex")),
});
Template.virtualList.events({
"scroll .list__container" (event, template) {
const target = event.target;
virtList.scrollOffset = $(target).scrollTop();
virtList.startOffset = () => Math.abs(virtList.scrollOffset / virtList.itemHeight);
virtList.endOffset = () => Math.abs(virtList.scrollOffset + virtList.containerHeight) / virtList.itemHeight;
virtList.startIndex = () => Math.floor(virtList.startOffset());
virtList.endIndex = () => Math.ceil(virtList.endOffset());
Session.set("startIndex", virtList.startIndex());
Session.set("endIndex", virtList.endIndex());
}
});
const visibleItems = (startIndex, endIndex) => virtList.items.slice(startIndex, endIndex).map((element, i) => {
let index = i + startIndex;
let top = (virtList.itemHeight * index);
return {
name: element.name,
style: top,
};
});