无法访问Ember的类变量

时间:2018-02-02 16:27:39

标签: javascript ember.js ember-cli

如何将变量正确传递给Ember的类?

控制器:

import Controller from '@ember/controller';
import Object from '@ember/object';

function totalVotes(company) {
  return company.upvotes + company.downvotes;
}

function calcPercent(company) {
    return (company.upvotes * 100 / (company.upvotes + company.downvotes)).toFixed(2);
}

function percentComparator(a, b) {
    return calcPercent(b) - calcPercent(a);
}

var Company = Object.extend({
  score: function() {
    return (this.get('upvotes') * 100 / totalVotes(this)).toFixed(2);
  }.property('upvotes', 'downvotes')
});

var AppModel = Object.extend({
  topCompanies: function() {
    return this.get('companies')
      .sort(percentComparator)
      .slice(0, 8);
  }.property('companies.@each.upvotes', 'companies.@each.downvotes'),
});

var appModel = AppModel.create({
  companies: getCompaniesJSON().map(function(json) {
    return Company.create(json);
  })
});

export default Controller.extend({
  topCompanies: appModel.topCompanies,
});

模板:

<ul>
{{#each topCompanies as |company|}}
  <li>{{company.title}} {{company.score}}%</li>
{{/each}}
</ul>

浏览器控制台中的上述结果:

jquery.js:3827 Uncaught TypeError: Cannot read property 'sort' of undefined

this.get('companies')未定义。为什么?我将companies传递给AppModel.create。我做错了什么?

1 个答案:

答案 0 :(得分:0)

var appModel = AppModel.create({
  companies: getCompaniesJSON().map(function(json) {
    return Company.create(json);
  })
});

应该是这样的(未经测试):

var appModel = AppModel.create({
  init() {
    this._super(...arguments);
    this.set('companies', getCompaniesJSON().map((json) => {
      return Company.create(json);
    });
  }
});

我假设代码以这种方式编写(带有全局变量)用于说明目的,因此我将忽略代码示例中可能不存在于您的实际代码中的其他问题,例如属性你的控制器需要是一个computed.alias而不是直接赋值等。