0

コントローラーの初期プロパティ値に基づいてビューのテンプレートを選択する必要がある場合があります。したがって、ビューの init フック内にいる間にコントローラーにアクセスする必要がありますが、コントローラーにアクセスすると「null」が返されます。

MyApp.ApplicationController = Em.Controller.extend({
  templateVersion: 'small'
});

MyApp.ApplicationView = Em.View.extend({
  init: function(){
    this._super();
    console.log('Controller is: ',this.get('controller'));
    if(this.get('controller').get('templateVersion') == 'small')
    {
      this.set('templateName', 'application-small');
    } else {
      this.set('templateName', 'application-bigger');
    }
  }
});

これは実際のケースではなく、実際のシナリオの例です。例として、ここでjsbinをセットアップしました

4

1 に答える 1

2

これを行うより適切な方法はtemplateName、次のように を動的に決定することだと思います。

MyApp.ApplicationView = Ember.View.extend({
  templateName: function() {
    if (this.get("controller.templateVersion") == "small") {
        return "application-small";
    } else {
        return "application-bigger";
    }
  }.property('controller.templateVersion')
});

このようにすると、関数にフックする必要がinitないため、コントローラーのプロパティを使用できなくなります。

ここに更新されたjsbin があります。

アップデート

あなたの最後のコメントの後、私はあなたのユースケースを機能させるために遅延が重要な部分であることに気付きましtemplateVersiontemplateName。を表示して呼び出しますrerender

MyApp.ApplicationView = Ember.View.extend({
  templateName: function() {
    if (this.get("controller.templateVersion") == "small") {
      return "application-small";
    } else {
      return "application-bigger";
    }
  }.property('controller.templateVersion'),
  templateChanged: function() {
    this.rerender();
  }.observes('templateName')
});

そして、ここに新しいバージョンの別のjsbinがあり、シミュレートされた遅延は 2 秒ですが、値は何でもかまいません。

それが役に立てば幸い。

于 2013-08-02T07:41:49.530 に答える