【问题标题】:Accessing iron router data from helper functions从辅助函数访问 Iron 路由器数据
【发布时间】:2015-04-04 05:20:13
【问题描述】:

请参考以下代码:

Router.route('/posts/:_id', function () {
   this.render('Post', {
     to: 'content',
     data: function () {
       return Posts.findOne({id: this.params._id});
     }
   });
 });

如果 Post 对象在 MongoDB 中有 titlebody 文件,我可以从 Post.html 模板访问它们,例如

<h4>Post title: {{title}}</h4>
<h3>Post body: {{body}}</h4>

我想在模板帮助函数中从Post.js 访问Post 对象。有可能吗?

更新: 根据这个问题:Meteor data-context with iron-router,我可以像这样访问data 变量:

 Template.Post.rendered = function() {
    console.log(this.data)
  }

有没有办法在Template.Post.events 内部做到这一点?

【问题讨论】:

    标签: meteor


    【解决方案1】:

    您似乎正在寻找Template.currentData() 方法。

    Template.example.events({
        'click #test':function(e,t){
          console.log(Template.currentData())
        }
     })
    

    update 好像使用 currentData 有不同的行为取决于情况check this

    所以看起来如果你想使用它,你应该在一个 DOM 元素中。

    Template.post.events({
      'click h4':function(){
        console.log(Template.currentData()) // and should return the title.
      }
    })
    

    根据 stubalio 所说。

    在事件处理程序中,返回元素的数据上下文 触发事件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-30
      • 2022-08-19
      相关资源
      最近更新 更多