流星 - 返回异步函数车把模板?

流星 - 返回异步函数车把模板?

问题描述:

我想生成基于一个Flickr API调用一个Flickr URL,然后该结果返回到handlebars.js模板。我在努力找到解决异步进程的方法。

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.

我试图创建一个回调函数,但我仍不确定如何得到一个定义的对象或变量到HTML模板。

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.

下面是code为Flickr的API函数:

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();
    }
});};

我的模板code是这样的:

My template code is this:

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

但是,这仍然让我卡住,没能获得一个定义的对象到我的HTML,这是codeD这样:

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>

使用会话作为中介。它是反应性的,以便一旦其设定它会改变与新的数据的模板:

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)
    });
}

所以创建创建模板时运行方法将被运行 FlickrRandomPhotoFromSet ,返回结果时,它会设置会话哈希这反过来会尽快结果被接收设置背景。

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.

小心你的 FlickrRandomPhotoFromSet 太,我没有注意到你不得不为 FlickrObject 传递给一个说法回调。

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