Meteor 流星模板事件,如何获取导致事件的对象?
我有一些类似于以下的代码: 在myapp.html中Meteor 流星模板事件,如何获取导致事件的对象?,meteor,Meteor,我有一些类似于以下的代码: 在myapp.html中 <template name="problems"> <div class="problems"> {{#each problems}} {{> problem}} {{/each}} </div> </template <template name="problem"> <div class="prob
<template name="problems">
<div class="problems">
{{#each problems}}
{{> problem}}
{{/each}}
</div>
</template
<template name="problem">
<div class="problem">
<div class="problem-text" id={{_id}}>{{text}}</div>
</div>
</template>
在这种情况下,我想获取匹配的.问题文本的id,并单击它
我想知道生成事件的“对象”?我该怎么做 试试这个:
Template.problem.events = {
'click .problem-text' : function () {
var user_id = Session.get('user_id');
// how to get problem_id of clicked item?
Router.gotoProblem(user_id, this._id);
}
};
您可以使用此引用访问问题对象:
Template.problem.events = {
/**
* Handles problem text click.
* @param {jQuery.Event} event
*/
'click .problem-text' : function (event) {
/*
Here this is a reference to the problem object
and you have jQuery.Event object as the event argument.
*/
console.log(this, arguments);
var user_id = Session.get('user_id');
var problem = this;
// how to get problem_id of clicked item?
Router.gotoProblem(user_id, /** problem_id */problem._id);
}
};
此问题的选定答案将仅获得
\u id
,如果模板中使用\u id
,则也将获得该id
所以最好使用,event.target
,它将给出完整的对象。因此可以与jQuery或MooTools一起使用
Template.top_nav.events({
'mousedown, .nav li a': function(evt){
console.log('the class of object that was clicked is ' + $(evt.target).attr("class"));
}
})
根据Meteor文档,他们在“this”对象中接收当前模板数据。我投了赞成票,因为这是真正的答案。将会话用于这样的事情是一种黑客行为。不确定“this”引用将为您提供助手检索到的对象中的数据。我认为这个问题与如何获取html对象更相关。在这种情况下,“event.target”是正确的方法。然而,将这两种方法都考虑在内是很好的。有时,当您想从反应数据重新渲染时,会使用“会话破解”。只是为了防止一些错误。请注意,使用event.target将为您提供单击的元素,因此在本例中,它可能返回一个span,该span是链接上的子级。使用event.currentTarget接收您正在侦听的元素。
Template.top_nav.events({
'mousedown, .nav li a': function(evt){
console.log('the class of object that was clicked is ' + $(evt.target).attr("class"));
}
})