【问题标题】:Helper variable undefined from router data从路由器数据中未定义的辅助变量
【发布时间】:2015-03-19 13:09:00
【问题描述】:

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

这是我的路线,您可以看到数据上下文包括根据存储在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 iron-router


    【解决方案1】:

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

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

    【讨论】:

    • 嗯,我也是这么想的。好的,很公平,我现在必须解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-30
    • 2016-10-24
    • 2019-11-10
    • 2020-01-27
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    相关资源
    最近更新 更多