在页面加载

时间:2016-09-29 19:06:06

标签: ember.js

首先,我目前的版本:

Ember      : 2.8.1
Ember Data : 2.8.1
jQuery     : 3.1.1

我在控制器中使用查询参数。如果用户转到assignments?strm=1292,则会调用strm,计算term,和计算filteredClusters。但是,filteredClusters在初始页面加载时将为空(例如,我使用浏览器导航到/assignments?strm=1292)。只有在调用selectStrm操作来更新strm查询参数后,filteredClusters才会开始返回结果。

我的assignments索引控制器如下所示:

import Ember from 'ember';

export default Ember.Controller.extend({
  queryParams: ['strm', 'cluster', 'title'],
  strm: null,
  cluster: null,
  title: null,

  term: Ember.computed('strm', function() {
    var strm = this.get('strm');
    var terms = this.get('model.terms');

    return strm ? terms.filterBy('strm', strm)[0] : null;
  }),

  filteredClusters: Ember.computed('term', 'model', function() {
    var term = this.get('term');
    var clusters = this.get('model.clusters');

    if(term) {
      return clusters.filter( (cluster, index, clusters) => {
        var terms = cluster.get('terms');

        return terms.mapBy('strm').includes(term.get('strm'));
      });
    } else {
      return clusters;
    }
  }),

  actions: {
    selectStrm: function(strms) {
      var strm = strms[0];
      this.set('strm', strm);
    }
  }
});

如何在初始页面加载时加载filteredClusters

感谢您提供任何和所有信息。

1 个答案:

答案 0 :(得分:1)

Probably your problem is that filteredClusters has the wrong dependencies. If model is available, are you sure that model.clusters and terms on each cluster is already loaded? Is something a async relationship?

Probably you would need a CP dependency like model.clusters.@each.terms.@each.strm. However this will not work since a double @each is not supported.

For now lets assume you have three models: assignment, cluster and term:

assignment

clusters: DS.hasMany('cluster')

cluster

terms: DS.hasMany('term')

term

strm: DS.attr()

now how to get rid of this double-@each? The answer is simple: Have a CP on the assignment that returns all terms of all clusters:

assignment:

terms: Ember.computed('clusters.@each.terms', {
  get() {
    return get(this, 'clusters')
      .map(c => get(c, 'terms'))
      .reduce((a,b) => [...a, ...b], []);
  }
}),

and now you can use model.terms.@each.strm as a dependency key for filteredClusters. This will force the CP to recompute when the clusters or terms are loaded.