【问题标题】:Getting the right data context in a Meteor template event handler在 Meteor 模板事件处理程序中获取正确的数据上下文
【发布时间】:2016-08-20 11:56:57
【问题描述】:

我正在使用 Meteor 1.3.1,并且我正在做一些实验来获取事件侦听器块中的数据上下文,这是我的代码:

  

var objs=[ 
      { a:"a1", b:"b1", yes:true },
      { a:"a2", b:"b2" },
      { a:"a3", b:"b3", yes:true },]


Template.tt.helpers({
  objs: objs
})

Template.tt.events({
  'click .b'(event, template) {
	console.log(Template.currentData().a);   //---> undefined
	console.log(template.data.a);            //---> undefined
    console.log(Template.parentData(0).a);   //---> undefined
	console.log(this);                       //---> Window Obj
  } 
})
<template name="tt">
{{#each objs}}
  <h1>a={{a}}, b={{b}}</h1> 
  {{#if yes}}
    <button class="b">b</button>{{yes}}
  {{/if}}
{{/each}}
</template>

我想获取a 键的值,但有几种方法都失败了。

【问题讨论】:

    标签: templates events meteor


    【解决方案1】:

    这个问题的常见模式是创建一个嵌套模板并将事件模板附加到它:

    html:

    <template name="tt">
      {{#each objs}}
        {{> inner}}
      {{/each}}
    </template>
    
    <template name="inner">
    <h1>a={{a}}, b={{b}}</h1> 
    {{#if yes}}
      <button class="b">b</button>{{yes}}
    {{/if}}
    </template>
    

    js:

    Template.inner.events({
      'click .b' (event, template) {
        console.log(this.a); //will be "a"
      } 
    })
    

    【讨论】:

    • 非常感谢,奇怪的是我没有找到这个解决方法。那么这是来自流星的某种错误吗?
    • 不是错误。在事件处理程序中this 是模板的数据上下文。如果没有特定的数据上下文,那么上下文就是窗口对象。
    猜你喜欢
    • 2013-02-14
    • 2015-11-06
    • 2016-06-28
    • 1970-01-01
    • 2015-10-07
    • 2015-03-13
    • 1970-01-01
    • 1970-01-01
    • 2015-03-07
    相关资源
    最近更新 更多