反应性变量在定义时是未定义的

Reactive variable is undefined when it is defined

本文关键字:未定义 定义 变量      更新时间:2023-09-26

我想得到一些帮助调试的情况下,一个反应变量是未定义的,当它已经被定义。

这段代码将一个反应变量附加到模板实例,并在template.autorun()中使用该变量。

Template.home.onCreated(function () {
  this.limit = new ReactiveVar(15);
  this.autorun(function () {
    this.subscribe('recent-topics', this.limit.get());
  });
});

当我第一次加载模板时,我希望模板使用参数15订阅recent-topics。但是,代码抛出了一个错误:

Uncaught TypeError: Cannot read property 'get' of undefined

知道为什么吗?

只是为了传播ES6的乐趣:

Template.home.onCreated(function () {
  this.limit = new ReactiveVar(15);
  this.autorun(() => {
    this.subscribe('recent-topics', this.limit.get());
  });
});

确保您添加了grigio:babel包,并且您的Javascript文件以.es6.js.es6.jsx结尾。

在ES6(又名ECMAScript 6)中,有一个新的"胖箭头"语法,与CoffeeScript的实现非常相似。在ES6中,当你这样做时:

someFunc = function () {
  anotherThing((var1, var2) => {
    this.thing = true;
  });
};

和下面的操作是一样的:

someFunc = function () {
  var self = this;
  anotherThing(function (var1, var2) {
    self.thing = true;
  });
};

这是一个范围问题。

在您的跟踪器内部。Autorun,这不再是指模板,而是Autorun的回调函数。在自动运行中,尝试调用Template.instance().limit.get()。

比使用Template.instance().limit.get() (ryan's answer)要好

你应该这样做:

Template.home.onCreated(function () {
  var self = this;
  self.limit = new ReactiveVar(15);
  self.autorun(function () {
    self.subscribe('recent-topics', self.limit.get());
  });
});