Meteor不接受getJson之外的div调用



Meteor.js有着非常奇特的体验。我的代码是这样的:

Template.mytemplate.rendered = function(){
$.getJSON('http://ip-api.com/json/?callback=?', function(lingo){
$('.location').text(" " + lingo.zip + ", " + lingo.city);
});
};

基本上,我使用API获取JSON信息,并将其放入我的$('.location')div中。然而,没有的是这个代码。

var tree = $('.location').text();
$('.repeat').text(tree);

具体来说,当我把这些代码放在getJSON函数之外时,它就不起作用了。所以这样做。。。

Template.mytemplate.rendered = function(){
$.getJSON('http://ip-api.com/json/?callback=?', function(lingo){
$('.location').text(" " + lingo.zip + ", " + lingo.city);
});

var tree = $('.location').text();
$('.repeat').text(tree);
};

以空的CCD_ 2结束。然而,如果我像这样重新格式化…

Template.mytemplate.rendered = function(){
$.getJSON('http://ip-api.com/json/?callback=?', function(lingo){
$('.location').text(" " + lingo.zip + ", " + lingo.city);
var tree = $('.location').text();
$('.repeat').text(tree);
});
};

然后,我突然能够检索我的div class="location"的属性,并将其放在我的div class="repeat"上。我想知道为什么会这样。

当div字符串包含json内容时,我不想在getJSON函数下面严格调用它们。

用于将location复制到repeat元素的jQuery代码将在初始化'.location'元素之前执行。

//rendered is old API.
Template.mytemplate.onRendered(function(){
$.getJSON('http://ip-api.com/json/?callback=?', function resultFn(lingo){
  //2. after some time this code will be executed
  $('.location').text(" " + lingo.zip + ", " + lingo.city);
});
  //1. code below will be executed first
  var tree = $('.location').text();
  $('.repeat').text(tree);
});

为什么?"getJSON"调用需要一些时间才能执行,因为它通过网络上传一些外部数据。因此,您的回调"resultFn"将延迟执行。这就是为什么最后两行将首先执行。

此外,使用jquery将数据放入模板中并不是真正的Meteor方式。我能想到的解决方案是:

<template name="myTemplate">
  <div class="location">
  {{location}}
  </div>
  <div class="repeat">
  {{location}}
  </div>
</template>

逻辑:

Template.myTemplate.onCreated(function(){
     this.location = new ReactiveVar(); //reactive-var package
     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();
  }
});

所以,现在您的数据以反应方式呈现,您可以随时通过更改反应变量的值来更改它。

最新更新