Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor - return asynchronous function to handlebar template?

I am trying to generate a Flickr url based on a Flickr API call, and then return that result to a handlebars.js template. I am struggling to find a way around asynchronous processes.

I have tried to create a callback function, but I am still uncertain how to get a defined object or variable into 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 this still leaves me stuck, not able to get a defined object into my HTML, which is coded as such:

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

like image 609
songololo Avatar asked May 19 '13 06:05

songololo


1 Answers

Use Session as an intermediary. It is reactive so as soon as its set it will change 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)
    });
}

So the created method will be run when the template is created to run FlickrRandomPhotoFromSet, when the result is returned it will set the Session hash which in turn will set the background as soon as the result is received.

Be careful with your FlickrRandomPhotoFromSet too, I didn't notice you had an argument for FlickrObject to pass to the callback.

like image 194
Tarang Avatar answered Sep 22 '22 09:09

Tarang