【问题标题】:MeteorJS - event click after template.onRenderedMeteorJS - template.onRendered 之后的事件点击
【发布时间】:2015-07-26 11:23:53
【问题描述】:

我有一个模板,我想用 Meteor.template.event() 添加一个点击事件。问题是 .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 无法掌握它。

【问题讨论】:

  • 有没有办法通过 Blaze 在模板中插入 HTML 而不是使用onRendered
  • 你为什么不为你想在事件中做的任何事情创建一个单独的函数,并从事件和onRendered调用该函数?
  • @chazsolo 我对流星很陌生。我正在做 jQuery,因为我从我正在使用的 API 随机生成图像并将它们推入 DOM。它不是静态的。你知道我可以在哪里了解更多信息的链接吗? Petr 你的意思是辅助函数吗?
  • 我认为@Petr 的意思是使用helper 调用 API 并收集图像并返回它们,以便您可以在 Blaze 中迭代它们
  • 我不知道这是否是个好主意,但如果你们前往我的repo,您会看到我的代码。我正在使用一种算法来随机化 API 中的图像,将它们放入一个数组中,然后使用 jquery 将它们推入模板中。我不确定这是否是您正在寻找的答案

标签: javascript jquery meteor


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-11-17
    • 2015-07-18
    • 2012-05-17
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-12
    相关资源
    最近更新 更多