在Ember控制器中访问变量

时间:2017-11-13 19:27:47

标签: javascript ember.js

如何在Ember控制器中访问变量? 我尝试过这些方法,但它不起作用:

import ObjectController from '@ember/controller';
export default ObjectController.extend({

  currentPhase: 1,

  init: function () {
      var selfReference = this;
      this.set("currentPhase",1);
  },

  strings: {
      title: "Title",
      phase1: "Fase " + selfReference.get("currentPhase"),
      phase2: "Fase " + currentPhase
  }
});

2 个答案:

答案 0 :(得分:1)

对于这种情况,您可以使用computed property

import Controller from '@ember/controller';
import { computed } from '@ember/object';

export default Controller.extend({
  currentPhase: 1,

  strings: computed('currentPhase', function() {
    let currentPhase = this.get('currentPhase');
    return {
      title: "Title",
      phase1: `Phase ${currentPhase}`,
      phase2: `Phase ${currentPhase}`
    }
  }
});

答案 1 :(得分:0)

在您的情况下,您已在init函数中定义了selfReference,但您试图从禁止的函数外部访问它。要从函数外部到达它,您需要使用set函数将其设置为变量。您也可以考虑将strings定义为computed property。看一下这个twiddle