问题描述
我正在开发一个 Meteor 项目,该项目使用 Sessions 进行自定义分页.渲染所述项目内容的模板使用 ellipsis.js 和 highlight.js 来做一些 DOM 格式化.代码看起来像这样:
I am working on a Meteor project that has come custom Pagination using Sessions. The template rendering the contents of said items is using ellipsis.js and highlight.js to do some DOM formatting. The code looks something like thus:
if (Meteor.isClient) {
Meteor.startup(function () {
Session.setDefault("homePageSize", 10);
Session.setDefault("homePageStart", 0);
});
}
Template.home.articlesPaginated = function() {
return Articles.find({published: true}, {sort: {post_date: -1}, skip: Session.get("homePageStart"), limit: Session.get("homePageSize")});
}
Template.home.rendered = function() {
// Setup ellipsis
$('.ellipsis').dotdotdot({
ellipsis: '...',
wrap: 'word',
fallbackToLetter: true,
after: $('a.blog_continue')
});
// Setup highlight.js
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
}
Template.home.events({
'click .next': function(event) {
var offset = Session.get("homePageStart") + Session.get("homePageSize");
if (offset < 0) {
offset = 0;
}
Session.set("homePageStart", offset);
},
'click .prev': function(event) {
var offset = Session.get("homePageStart") - Session.get("homePageSize");
if (offset < 0) {
offset = 0;
}
Session.set("homePageStart", offset);
}
});
分页工作正常,但是一旦模板重新渲染,我就会丢失所有 ellipsis.js 和 highlight.js 格式.我知道明显的原因是 DOM 发生了变化,并且由于 Template.render 只预先运行一次,并且不会在模板重新渲染时发生,因此未应用 DOM 更新.那么,在模板完成后触发 ellipsis.js 和 highlight.js 的最佳方法是什么,这样每次模板重新渲染时都会重新调用它?
Pagination is working just fine, but as soon as the Template re-renders I loose all the ellipsis.js and highlight.js formatting. I know the obvious reason is that the DOM has changed, and since the Template.render only runs once up-front and doesn't happen when the Template re-renders the DOM updates are not being applied. So, what is the best way to trigger ellipsis.js and highlight.js after the Template is done such that it gets re-called everytime the Template re-renders?
推荐答案
如果您可以将 文章
放入另一个模板中,那么您就可以在插入时单独应用格式.
If you can put your Articles
into another template, then you could apply formatting individually as they are inserted.
Template.article.rendered = function () {
// Setup ellipsis
this.$('.ellipsis').dotdotdot({
ellipsis: '...',
wrap: 'word',
fallbackToLetter: true,
after: $('a.blog_continue')
});
// Setup highlight.js
this.$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
};
假设您的模板看起来像这样.
Assuming your template looks something like this.
<template name="home">
...
{{#each articlesPaginated}}
{{> article}}
{{/each}}
{{> paginationControls}}
...
</template>
这有一个额外的好处,就是将格式范围限定为文章,而不是整个 DOM.
This has the added benefit of scoping the formatting to just the articles, rather than the entire DOM.
这篇关于模板刷新时的流星事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!