2015-04-04 160 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. 
     } 
    }); 
}