在使用Meteor进行异步服务器端调用时,如何使辅助函数无效?

时间:2015-10-09 11:32:15

标签: meteor

下面是我的HTML,Client和Server JS。我遇到的问题是,起初我的帮助函数没有返回任何内容,因为服务器调用需要一秒钟才能返回数据。

我需要的是当数据最终在辅助函数中返回给客户端时HTML更新的方法。

HTML

{{#each matches}}
    {{>match}}
{{/each}}

客户端JS

    Template.matches.helpers({
    matches: function() {
        Meteor.call('callAuthorize', function(error, response){
            return response.matches;
        })
    },

服务器JS

Meteor.methods({

    callAuthorize: function () {
        //load Future
        Future = Npm.require('fibers/future');
        var myFuture = new Future();
        //call the function and store its result
        client.authorize(
            "FB_Auth",
            "FB_Id",
            function () {
                client.getHistory( function (error, data) {
                    myFuture.return(data);
                });
            })
        return myFuture.wait();
    }
});
}

1 个答案:

答案 0 :(得分:2)

你有几个选择。例如,您可以将方法的结果存储在Session变量中,而不是返回此变量:

if (Meteor.isClient) {
  Meteor.call('callAuthorize', function(error, response){
    Session.set('authorizeMatches') = response.matches;
  });

  Template.matches.helpers({
    matches: function() {
      return Session.get('authorizeMatches');
    }
  });
}

或者,使用reactive variable

  Template.matches.onCreated(function() {
    this.authorizeMatches = new ReactiveVar;
    Meteor.call('callAuthorize', function(error, response){
      this.authorizeMatches.set(response.matches);
    });
  });

  Template.matches.helpers({
    matches: function() {
      return Template.instance().authorizeMatches.get();
    }
  });

您还可以使用simple:reactive-method包:

Template.matches.helpers({
  matches: function() {
    var result = ReactiveMethod.call('callAuthorize');
    return result.matches;
  }
});

当然,在这两个选项中,您的助手永远不会自行更新:只有订阅/出版物才能让客户知道他们的数据何时更新,方法不会这样做。如果您希望您的方法重复该facebook API调用,则必须使用轮询。例如:

Meteor.setInterval(function() {
  Meteor.call('callAuthorize', function(error, response){
    Session.set('authorizeMatches') = response.matches;
  });
}, 5000); // every 5 seconds
相关问题