Edgar
Edgar

Reputation: 927

Meteor.js Re-use template with different data

I have a virtualList template that I want to reuse with a different data (virtList.items). How can I make it abstract to a data i.e. make it behave more like a module?

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,
    };
});

Upvotes: 0

Views: 50

Answers (1)

Faysal Ahmed
Faysal Ahmed

Reputation: 1542

look at the official documentation. You are allowed to pass data context along with template.

Meteor Docs for template data context

Upvotes: 1

Related Questions