我的Meteor应用程序无法通过Pub Sub

时间:2015-05-16 00:45:20

标签: javascript meteor

我已经完成了基本的排行榜应用并阅读了进一步的文档,最后决定使用本教程作为指南制作我自己的应用:http://meteorcapture.com/publishing-data-from-an-external-api/

我的当前代码似乎可以解决,直到将数据传递回客户端。我似乎无法从服务器获取数据。即使我订阅并发布所有设置。

我已经减少并简化了我的代码,但减少了错误点:

MyMp = new Mongo.Collection('mymp');

if (Meteor.isClient) {
  Session.setDefault('searching', false);

  Tracker.autorun(function(){
    if(Session.get('postcode')){
      var twfyHandle = Meteor.subscribe('twfySearch', Session.get('postcode'));
      Session.set('searching', ! twfyHandle.ready());
    }
  });

  Template.searchForm.events({
    'submit form': function(event, template) {
      event.preventDefault();
      var postcode = template.$('input[type=text]').val();

      if (postcode) {
        Session.set('postcode', postcode);
      }
    }
  });

  Template.body.helpers({
    mymp: function() {
      return MyMp.find();
    },
    searching: function() {
      return Session.get('searching');
    }
  });
}

if (Meteor.isServer) {
  Meteor.publish('twfySearch', function(postcode){

    console.log(postcode); // this received ok
    var self = this;

    var mp = {first_name: 'Test Name', party: 'Labour'}

    self.added('mymp', Random.id(), mp);
    self.ready();
  });
}

我的HTML文件中的模板:

<body>
    <h1>Get Details on your MP and Constituency</h1>
    <h2>Enter your post code below</h2>

    {{> searchForm }}

    {{#if searching }}
        <p>Searching...</p>
    {{else}}
    <div class="">
    {{> twfyResults }}
    </div>
    {{/if}}
</body>

<template name="twfyResults">
    {{ mp.first_name }}
</template>

<template name="searchForm">
<form>
    <input type="text" name="postcode" id="postcode" />
    <input type="submit" value="Search" />
</form>
</template>

我将邮政编码传递给服务器,服务器填充了一个基本的JSON对象&#39; mp&#39;在发布方法下并使其准备就绪()。

这是失败的地方。虽然我的console.log()调用显示服务器正在获取邮政编码并创建mp对象。客户没有得到任何回报!

更新: 我已设法在浏览器控制台MyMp.findOne()中手动运行,并返回服务器创建的对象。但是,我的模板似乎无法访问此对象。还有&#39; mp&#39;对象本身并不存在。

1 个答案:

答案 0 :(得分:0)

我在代码中发现了三个错误。

  1. 我假设用于访问发送回的数据的模板对象在前端具有与在服务器(mp)中相同的名称。相反,我应该尝试访问帮助程序名称“mymp”。
  2. 通过更改twfyResults模板以引用辅助方法来解决此问题:

    <template name="twfyResults">
        {{ mymp.first_name }}
    </template>
    
    1. 我对twfyResults的帮助是在错误的背景下。所以我重写了我的助手:
    2. Template.body.helpers({

          searching: function() {
              console.log(this);
              return Session.get('searching');
          }
      });
      
      Template.twfyResults.helpers({
          mymp: function() {
              return MyMp.findOne();
          }
      });
      
      1. 但仅凭上述情况还不够。我还必须更改“mymp”帮助器才能返回一个结果,因为在这种情况下只返回一个结果。这样我就可以用上面的方式访问我的对象变量。所以我的助手改为findOne(),而不是像上面那样找到。