Meteor - return asynchronous function to handlebar template?

孤街浪徒 提交于 2019-12-18 13:26:37

问题


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>


回答1:


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.



来源:https://stackoverflow.com/questions/16632050/meteor-return-asynchronous-function-to-handlebar-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!