代码之家  ›  专栏  ›  技术社区  ›  derek

这订阅和Template.instance()。订阅不工作

  •  0
  • derek  · 技术社区  · 9 年前

    我正在使用流星1.4。

    Template.showProducts.onCreated(() => {
      var handle = Meteor.subscribe("products");
      //not working: var handle = this.subscribe("products");
      //not working: var handle = Template.instance().subscribe("products");
    
      Tracker.autorun(() => {
      //not working: this.autorun
    
        const isReady = Meteor.ready();
        //not working: this.subscriptionsReady()
    
        if(isReady){
          const products = Products.find().fetch();
          Session.set("prods", products);
        }
      });
    });
    

    如果我使用“this.subscribe”,我得到:

    未捕获类型错误:_this。订阅不是一个函数

    如果我使用“Template.instance()”,我得到:

    无法读取null的属性“subscriptionsReady”

    2 回复  |  直到 9 年前
        1
  •  2
  •   user3374348    9 年前

    如果使用箭头函数,则 this 哪一颗流星试图通过,就丢失了。相反,请使用常规匿名函数( function () { ... }

    然后,您应该使用 this.autorun Tracker.autorun Template.instance

        2
  •  2
  •   richsilv    9 年前

    问题是你通过了 onCreated 处理程序一个箭头函数,它不允许绑定 this ( reference ). 因此,Meteor无法正确绑定它刚刚创建的模板实例,您的订阅(以及其他各种事情)将失败。

    这个问题就要过去了 曾经创造 一个传统的JS函数:

    Template.showProducts.onCreated(function () {
      ...