Meteor - returns an asynchronous function to a rudder pattern?

I am trying to create a Flickr url based on a call to the Flickr API and then return this result to the handlebars.js template. I am struggling to find a way to asynchronous processes.

I tried to create a callback function, but I'm still not sure how to get a specific object or variable in the HTML template.

Here is the code for the Flickr API function:

var FlickrRandomPhotoFromSet = function(setID,callback){ Meteor.http.call("GET","http://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&api_key="+apiKey+"&photoset_id="+setID+"&format=json&nojsoncallback=1",function (error, result) { if (result.statusCode === 200) var photoResult = JSON.parse(result.content); var photoCount = photoResult.photoset.total; var randomPhoto = Math.floor((Math.random()*photoCount)+1); var selectedPhoto = photoResult.photoset.photo[randomPhoto]; var imageURL = "<img src=http://farm"+selectedPhoto.farm+".staticflickr.com/"+selectedPhoto.server+"/"+selectedPhoto.id+"_"+selectedPhoto.secret+"_b.jpg/>"; FlickrObject.random = imageURL; } if (callback && typeof(callback)==="function") { callback(); } });}; 

My template code is this:

 Template.backgroundImage.background = function(){ FlickrRandomPhotoFromSet(setID,function(){ return FlickrObject; }); }; 

But that still leaves me stuck, unable to get a specific object in my HTML, which is encoded as such:

 <template name="backgroundImage"> <div id="background"> {{random}} </div> 

+6
source share
1 answer

Use Session as an intermediary. He reacts as soon as his set changes the template with the new data:

 Template.backgroundImage.background = function(){ return Session.get("FlickrObject"); }; Template.backgroundImage.created = function() { FlickrRandomPhotoFromSet(setID,function(){ Session.set("FlickrObject", FlickrObject) }); } 

Thus, the created method will be launched when creating the template to run FlickrRandomPhotoFromSet , when the result is returned, it will set the hash of the session, which in turn will set the background as soon as the result is received.

Be careful with your FlickrRandomPhotoFromSet too, I didn’t notice that you have an argument for FlickrObject to jump to the callback.

+10
source

Source: https://habr.com/ru/post/945344/


All Articles