2016-05-04 10 views
0

Meteorを使用して、与えられたテンプレート(この場合はlocation)の結果を取得し、それを別のJS操作の変数として使用したいと考えています。これの具体的なアプリケーションはAPI用です。上記のコードを使用してMeteorJSは以前の関数からJSの結果を取得しますか?

Template.myTemplate.onCreated(function(){ 
    this.location = new ReactiveVar(); 
    var self = this; 
    $.getJSON('http://ip-api.com/json/?callback=?', function(lingo) { 
    self.location.set(lingo.zip + ", " + lingo.city); 
    }); 
}); 

Template.myTemplate.helpers({ 
    location: function(){ 
    return Template.instance().location.get();} 
}); 

、私はHTMLで{{location}}を割り当てられた領域の応答を取得します。今、{{location}}の値を使用して文字列に変換し、cheddarという名前の変数として使用したいと考えています。例えばだから:

Template.anotherTemplate.onCreated(function(){ 
    this.zangrief = new ReactiveVar(); 
    var self = this; 
    var cheddar = Template.instance().location.get(); 
    $.getJSON('http://www.anotherapi'+cheddar+'myapikey', function(red) { 
    self.zangrief.set(red.stuff); 
    }); 
}); 

そのポイントは、API#1を使用して自分の位置を取得し、API#2に関連するデータを取得するためにそれを使用することです。この例では、返信ヘルパーコードvar cheddarを使用して、最初のテンプレート{{location}}の応答を取得しています。これはうまくいかないので、私はそのようなことについてどうやって行くのか知りたい。

+2

理由は 'Template.instanceは()'を参照していることです。そして、それはdocs on namespacesもこのポストをチェックしwindow.myvar

//begining of the file var myvar; //template 1 Template.myTemplate.helpers({ location: function(){ myvar = Template.instance().location.get() return Template.instance().location.get();} }); //template 2 Template.anotherTemplate.onCreated(function(){ this.zangrief = new ReactiveVar(); var self = this; var cheddar = window.myvar //etc 

を介して他のテンプレートにアクセスできる必要があります現在のテンプレートのインスタンス名前の付いた2つのテンプレートがあり、それぞれが複数のインスタンスを持つことができます。 @shershenは彼の答えを指摘するので、両方のテンプレートで共有するスコープ内に変数を作成する必要があります。これに対する最も一般的な解決策は単純に 'Session'変数です。 –

答えて

関連する問題