MeteorJS - 在template.onRendered之后点击事件

时间:2015-05-14 18:01:32

标签: javascript jquery meteor

我有一个模板,我想用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无法掌握它。

1 个答案:

答案 0 :(得分:0)

好吧,所以我找到了解决这个问题的方法,它确实有效。这就是我现在想要的。我完全忽略了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

相关问题