Recently, I had a rather interesting encounter with Meteor.js. Let me walk you through my code snippet:
Template.mytemplate.rendered = function(){
$.getJSON('http://ip-api.com/json/?callback=?', function(lingo){
$('.location').text(" " + lingo.zip + ", " + lingo.city);
});
};
Essentially, I am utilizing an API to fetch JSON data and display it within my $('.location')
element. This part of the code functions as expected. However, the following code does not seem to work.
var tree = $('.location').text();
$('.repeat').text(tree);
More specifically, this code fails when placed outside the getJSON function. For instance...
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);
};
results in an empty div class="repeat"
. Curiously, if I rearrange the code as follows...
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);
});
};
Suddenly, I can access the content within my div class="location"
and transfer it to my div class="repeat"
. The reason behind this peculiar behavior eludes me.
I would prefer not to limit myself to placing my div manipulations strictly within the getJSON function whenever they involve JSON content.