MeteorJS从上一个函数中检索JS中的结果

MeteorJS retrieve result in JS from previous function?

本文关键字:JS 结果 检索 MeteorJS 上一个 函数      更新时间:2023-09-26

使用Meteor,我希望能够检索给定模板的结果,在本例中为location,并将其用作另一个JS操作中的变量。这一点的具体应用是针对API的。

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}}中的响应。这不起作用,所以我想知道这样的事情是怎么发生的。

如果是在客户端,那么您可以尝试以常规JS方式var myvar=XXX分配值;然后它应该可以通过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

查看关于名称空间的文档以及这篇文章:Meteor客户端中的变量作用域是什么?