[英]MeteorJS - event click after template.onRendered
我有一個模板,希望通過Meteor.template.event()向其中添加click事件。 問題是.event()無法正常工作,我無法掌握DOM。
我正在使用Meteor.template.onRendered()來顯示API數據,而我正在使用jQuery將數據推送到模板中。 然后,我想獲取一個通過jQuery生成的[name]選擇器,並使用Meteor.template.event()對其進行操作,但是它不起作用
//server Meteor.method()
incrementNormalPoints: function(err){
Points.upsert( {userId: this.userId}, { $inc : {normalPoints : 2} });
}
//client Meteor.template.onRendered().. this part works
Template.normalMode.onRendered(function(){
$("[name=imageGuess").append('<div class="flip"><div name="imageCard" class="card"><div class="face front"><img name="rightAnswer" id="theImg" class="img-responsive" src="'+imgArray[i]+'" /></div><div class="face back"><span class="center-glyphicon glyphicon glyphicon-ok"></div></div></div>');
}
Template.normalMode.events({
"click [name=rightAnswer]" : function(){
event.preventDefault();
Meteor.call("incrementNormalPoints");
console.log("hello");
}
});
希望我有道理。 目前,控制台在events()函數中的日志也不起作用。 我很確定這是因為DOM不存在而JS無法獲得它。
好的,所以我找到了解決此問題的方法,並且它可以工作。 目前我要的是哪一個。 我完全忽略了Meteor.events()並通過Meteor.onRendered()塊進行工作。
我制作了一個函數upsertNPoints(),該函數在服務器上“調用”我聲明的方法,並使用它將點向上插入到我的點表中。
//server Methods()
incrementNormalPoints: function(err){
Points.upsert( {userId: this.userId}, { $inc : {normalPoints : 2} });
if(err){
console.log(err);
}
},
//Upsert database using the call() method meteor provides on the client
function upsertNPoints(){
$("[name=rightAnswer]").on("click", function(){
Meteor.call("incrementNormalPoints");
location.reload(true);//this is just to reload the window after a click
});
}
upsertNPoints();
希望這對我遇到的這個怪異問題有幫助。 感謝您的建議@Petr和@chazsolo
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.