【发布时间】:2015-07-28 06:53:33
【问题描述】:
所以,我尝试使用的模板助手有问题。
我正在使用帮助器返回一个类,具体取决于数据库条目。 加载模板时它确实可以正常工作,但是当数据库条目更改(例如,单击按钮并且事件调用更新方法)时,帮助程序似乎不会重新运行。
我希望助手在点击事件调用更新方法时重新运行。
有什么想法吗?
模板:
<template name="modalPost">
<div id="modalPost" class="modal fade" role="dialog" aria-labelledby="gridSystemModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
[...]
<div class="modal-body">
<div class="row">
<div class="col-sm-5">
<div class="col-xs-12">
<a href="#" class="upvote btn btn-default {{upvotedClass}}">⬆</a>
<a href="#" class="downvote btn btn-default {{downvotedClass}}">⇩</a>
</div>
</div>
</div>
</div>
[...]
</div><!-- modal-content -->
</div><!-- modal-dialog -->
</div><!-- id: bugModal -->
助手:
Template.modalPost.helpers({
'upvotedClass': function() {
var userId = Meteor.userId();
if (userId && !_.include(this.upvoters, userId)) {
return 'upvotable';
} else if (userId && _.include(this.upvoters, userId)) {
return 'btn-success disabled';
} else {
return 'disabled';
}
},
'downvotedClass': function() {
var userId = Meteor.userId();
if (userId && !_.include(this.downvoters, userId)) {
return 'downvotable';
} else if (userId && _.include(this.downvoters, userId)) {
return 'btn-danger disabled';
} else {
return 'disabled';
}
}
});
事件:
Template.modalPost.events({
'click .upvotable': function(e, template) {
e.preventDefault();
Meteor.call('upvotePost', this._id);
},
'click .downvotable': function(e) {
e.preventDefault();
Meteor.call('downvotePost', this._id);
}
});
// 可能与问题无关,但为了方便:-)
方法:
Meteor.methods({
'upvotePost': function(post_id){
var post = Posts.findOne(post_id);
if (!post) {
console.log('error, post not found');
} else if (_.include(post.upvoters, this.userId)) { // if already upvoted
console.log('error, already upvoted this post');
} else if (_.include(post.downvoters, this.userId)) { // if downvoted before
Posts.update(post._id, {
$addToSet: {upvoters: this.userId},
$pull: {downvoters: this.userId},
$inc: {votes: 2}
});
} else { // if vote for first time
Posts.update(post._id, {
$addToSet: {upvoters: this.userId},
$pull: {downvoters: this.userId},
$inc: {votes: 1}
});
}
},
'downvotePost': function(post_id){
var post = Posts.findOne(post_id);
if (!post) {
console.log('error, post not found');
} else if (_.include(post.downvoters, this.userId)) { // if already downvoted
console.log('error, already downvoted this post');
} else if (_.include(post.upvoters, this.userId)) { // if upvoted before
Posts.update(post._id, {
$addToSet: {downvoters: this.userId},
$pull: {upvoters: this.userId},
$inc: {votes: -2}
});
} else { // if vote for first time
Posts.update(post._id, {
$addToSet: {downvoters: this.userId},
$inc: {votes: -1}
});
}
}
});
【问题讨论】:
标签: html templates meteor helper