路由器数据中未定义帮助程序变量



我正在基于Session变量检索Collection文档,然后将其作为一个名为store的变量通过iron:router数据上下文传递。问题是,它有时会返回undefined,就好像它没有及时为助手执行做好准备一样。如何确保在运行helper/template之前始终定义变量?

这是我的路线,您可以看到数据上下文包括基于存储在Session变量中的_id从集合中检索文档:

Router.route('/sales/pos', {
    name: 'sales.pos',
    template: 'pos',
    layoutTemplate:'defaultLayout',
    loadingTemplate: 'loading',
    waitOn: function() {
        return [
            Meteor.subscribe('products'),
            Meteor.subscribe('stores'),
            Meteor.subscribe('locations'),
            Meteor.subscribe('inventory')
        ];
    },
    data: function() {
        data = {
            currentTemplate: 'pos',
            store: Stores.findOne(Session.get('current-store-id'))
        }
        return data;
    }
});

这里有一个助手,它依赖于传递给模板的store变量:

Template.posProducts.helpers({
    'products': function() {
        var self = this;
        var storeLocationId = self.data.store.locationId;
        ... removed for brevity ...
        return products;
    }
});

这是Meteor中常见的问题。当您等待订阅准备就绪时,这并不意味着您的查找函数有时间返回某些内容。你可以用一些防御编码来解决它:

Template.posProducts.helpers({
  'products': function() {
    var self = this;
    var storeLocationId = self.data.store && self.data.store.locationId;
    if (storeLocationId) {
      ... removed for brevity ...
      return products;
    }
  }
});

最新更新