为什么助手会在Meteor中抛出异常

时间:2014-11-26 12:07:17

标签: meteor

流星应用。我有模板助手:

Template.channel.helpers({
channels: function() {
    var cursor = News.find({ }, {fields:  { title: 1 } }),
        firstChannel = cursor.fetch()[0];

    console.log(firstChannel);
    Session.set("channelId", firstChannel._id);

    return cursor;
}

});

我需要在Session中保存channelId,但是Meteor抛出异常。这个调试器在浏览器中:

undefined
debug.js:41 Exception in template helper: TypeError: Cannot read property '_id' of undefined
    at Object.Template.channel.helpers.channels (http://localhost:3000/client/lib/helpers.js?a55983adb497520dfef7f2a4a8692a7e13e1b4f6:11:46)
    at http://localhost:3000/packages/blaze.js?77c0809654ee3a10dcd5a4f961fb1437e7957d33:2693:16
    at http://localhost:3000/packages/blaze.js?77c0809654ee3a10dcd5a4f961fb1437e7957d33:1602:16
    at Object.Spacebars.call (http://localhost:3000/packages/spacebars.js?3c496d2950151d744a8574297b46d2763a123bdf:169:18)
    at http://localhost:3000/client/template.channel.js?44d590e72735f4cdd0f546df5204c94f8cc015f9:12:22
    at null.<anonymous> (http://localhost:3000/packages/blaze.js?77c0809654ee3a10dcd5a4f961fb1437e7957d33:2503:27)
    at http://localhost:3000/packages/blaze.js?77c0809654ee3a10dcd5a4f961fb1437e7957d33:1795:16
    at Object.Blaze._withCurrentView (http://localhost:3000/packages/blaze.js?77c0809654ee3a10dcd5a4f961fb1437e7957d33:2029:12)
    at viewAutorun (http://localhost:3000/packages/blaze.js?77c0809654ee3a10dcd5a4f961fb1437e7957d33:1794:18)
    at Tracker.Computation._compute (http://localhost:3000/packages/tracker.js?192a05cc46b867dadbe8bf90dd961f6f8fd1574f:288:36)
helpers.js?a55983adb497520dfef7f2a4a8692a7e13e1b4f6:10 
Object {title: "Яндекс.Новости: Выставки", _id: "ww2baqF7HhkrDTFA7"}

为什么console.log(firstChannel)首先放置“undefined”,并在异常后提出我期待的对象?为什么会抛出异常?

谢谢。

2 个答案:

答案 0 :(得分:2)

您的新闻文件不存在或者尚未到达客户端。您需要在路由控制器中wait on新闻订阅,或者需要添加guard。这是一个简单的解决方案:

Template.channel.helpers({
  channels: function() {
    var cursor = News.find({}, {fields: {title: 1}});
    var news = cursor.fetch();

    if (news && news[0]) {
      var firstChannel = news[0];
      console.log(firstChannel);
      // Note that you should do this in your route controller or
      // in an autorun. Helpers should not have side effects.
      Session.set("channelId", firstChannel._id);
    }

    return cursor;
  }
});

由于助手是被动的,因此一旦新闻文件可用,您的channels助手将重新运行。

如评论中所述,你的助手不应该有副作用。设置会话变量应该在路由控制器或autorun中完成。

答案 1 :(得分:0)

您想使用_id,并且您屏蔽了该字段,只有标题可见