Meteor.js重复使用具有不同数据的模板

时间:2016-05-19 09:49:33

标签: javascript meteor

我有一个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,
    };
});

1 个答案:

答案 0 :(得分:1)

查看官方文档。您可以将数据上下文与模板一起传递。

Meteor Docs for template data context