2015-04-04 60 views
1

我希望能够使用模板事件处理函数设置/获取模板对象的数据。我试图在模板呈现时设置一个变量,并希望稍后可以访问这个变量,在这种情况下,当模板中的某个元素被用户点击时,但它不起作用:如何获取模板对象数据以保持流星模板?

<template name="fooBar"> 
    <div class="some_element">CLICK ME</div> 
</template> 

Template.fooBar.rendered = function(){ 
    this.templateVar = "Hello"; 
} 

Template.fooBar.events({ 
    'click .some_element': function(e,t){ 
     alert(this.templateVar); // Should say 'Hello', but is 'undefined'. 
    } 
}); 
+0

您可以使用会话? – Ethaan 2015-04-04 19:40:09

+1

t.templateVar或Template.instance()。templateVar – Sindis 2015-04-04 19:41:12

+0

Template.instance在渲染和事件处理程序上获得了[不同行为](https://groups.google.com/forum/#!topic/meteor-talk/PrzfPlYKYjk) – Ethaan 2015-04-04 19:41:47

回答

0

按照由Sindis给出的建议,这是解决问题的最快方法:

而不是...

alert(this.templateVar); 

。 ..只是做...

alert(this.templateVar);alert(Template.instance().templateVar);

2

使用reactive-dict包,你可以这样做。

第一个添加它。

meteor add reactive-dict 

创建模板。 (注意即时通讯使用流星1.1版本)

if (Meteor.isClient) { 
    Template.hello.onRendered(function(){ 
     this.templateVar = new ReactiveDict(); //create the var templateVar 
    }) 

    Template.hello.onRendered(function(){ 

    this.templateVar.set("hi", "hello"); //give them a value 
    }) 

    Template.hello.events({ 
     'click .some_element': function(e,t){ 
     console.log(t.templateVar.get('hi')) //and print the value using the template instance. 
     } 
    }); 
}