我正在处理一个使用Sessions自定义分页的Meteor项目。呈现上述项目内容的模板使用ellipsis.js和Highlight.js进行一些DOM格式化。代码看起来像这样:
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仅预先运行一次,并且在重新渲染Template时未发生,因此未应用DOM更新。那么,在模板完成后触发ellipsis.js和Highlight.js以便每次重新渲染模板时都被调用的最佳方法是什么?
如果可以将其Articles
放入另一个模板,则可以在插入模板时分别应用格式。
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);
});
};
假设您的模板看起来像这样。
<template name="home">
...
{{#each articlesPaginated}}
{{> article}}
{{/each}}
{{> paginationControls}}
...
</template>
这具有将格式范围限定为仅文章而不是整个DOM的附加好处。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句