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

流星ES6脂肪箭头功能和“this”打开创建不工作[重复]

  •  1
  • fuzzybabybunny  · 技术社区  · 8 年前

    对不起,这里是ES6新手:

    Template.hello.onCreated( () => {
      // counter starts at 0
      this.counter = new ReactiveVar(0);
    });
    
    Template.hello.helpers({
      counter() {
        return Template.instance().counter.get();
      },
    });
    
    Template.hello.events({
      'click button'(event, instance) {
        // increment the counter when button is clicked
        instance.counter.set(instance.counter.get() + 1);
      },
    });
    

    当我点击按钮时,我得到 Cannot read property 'get' of undefined

    但当我这么做的时候

    Template.hello.onCreated( function(){
      // counter starts at 0
      this.counter = new ReactiveVar(0);
    });
    

    它工作得很好。

    所以ES6的胖箭头绑定 this 我没有得到的关键词?

    1 回复  |  直到 8 年前
        1
  •  4
  •   klaussner    8 年前

    当流星呼叫 onCreated 处理程序,它绑定函数的 this 值设置为模板实例。 Arrow functions 词法上 绑定 ,这意味着 window 。因此,您正在创建一个全局变量 counter 而不是将其分配给模板实例。

    对于 创建时 , onRendered 等等,使用箭头功能没有意义。