【问题标题】:Returning Server Side Data Wrapped in a Fiber to a Client Side Call with MeteorJS使用 MeteorJS 将封装在 Fiber 中的服务器端数据返回到客户端调用
【发布时间】:2014-03-25 15:35:30
【问题描述】:

我正在尝试让服务器端方法在浏览器控制台中返回推文 JSON 对象。到目前为止,我的应用程序可以从 Twitter API 中提取信息并将所有这些数据插入到集合中,但它不会将数据返回给调用。我已经用调用和方法进行了一系列测试来调试这个问题,我认为 Fiber 可能会改变这个调用/方法的工作方式。

http://sf-tweet-locator.meteor.com/

我希望能够从每个对象中提取经度和纬度,以便我可以在地图上放置每条推文位置的图钉。我不确定我的做法是否是“最佳”方式,但我愿意接受所有建议!

if (Meteor.isClient) {
  Meteor.call("tweets", function(error, results) {
    console.log(results); //results.data should be a JSON object
  });
}

Meteor.methods({
  Fiber = Npm.require('fibers');

  tweets: function(){
    Twit = new TwitMaker({
      consumer_key: '...',
      consumer_secret: '...',
      access_token: '...',
      access_token_secret: '...'
    });

    sanFrancisco = [ '-122.75', '36.8', '-121.75', '37.8' ];

    stream = Twit.stream('statuses/filter', { locations: sanFrancisco });

    var wrappedInsert = Meteor.bindEnvironment(function(tweet) {
      var userName = tweet.user.screen_name;
      var userTweet = tweet.text;
      console.log(userName + " says: " + userTweet);
      Posts.insert(tweet);
      return tweet;

    }, "Failed to insert tweet into Posts collection.");

    stream.on('tweet', function (tweet) {
      wrappedInsert(tweet);
      return tweet;
    });
  }, 
})

【问题讨论】:

  • 你想怎么做,你正在使用流 API,所以一些推文可能会稍晚一些。您只能返回通话一次。您希望哪些推文获得回报,第一条推文是什么?

标签: javascript meteor


【解决方案1】:

您可以将其作为出版物进行 - 这样您就不会将无用的数据插入到您的 Posts 集合中,

此示例创建一个发布,它将每条新推文发送到客户端上的local-tweets 集合。

您可以将queryId 传递给订阅/发布,如果您需要引用源查询,则在每个推文文档中返回它。

if (Meteor.isClient){
  var localTweets = new Meteor.Collection('local-tweets');

  Meteor.subscribe("tweets", [ '-122.75', '36.8', '-121.75', '37.8' ]);

  localTweets.observe({
    added: function(doc) { console.log('tweet received!', doc); }
  });
}

if (Meteor.isServer){
  Meteor.publish("tweets", function(bbox){
    var pub = this, stopped = false;
    var Twit = new TwitMaker({
      consumer_key: '...',
      consumer_secret: '...',
      access_token: '...',
      access_token_secret: '...'
    });
    stream = Twit.stream('statuses/filter', { locations: bbox });

    var publishTweet = Meteor.bindEnvironment(function(tweet) {
      if (stopped) return;
      pub.added("local-tweets", Random.id() /* or some other id*/, tweet);
    }, "Failed to tweet.");

    stream.on('tweet', publishTweet);

    this.ready()

    this.onStop(function(){
      /* any other cleanup? */
      stopped = true;
    });
  });

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-22
    相关资源
    最近更新 更多