Can't access Ember's class variable

半腔热情 提交于 2019-12-11 16:31:20

问题


How to properly pass a variable to an Ember's class?

Controller:

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,
});

Template:

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

The result of the above in the browser console:

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

this.get('companies') is undefined. Why? I'm passing companies to AppModel.create. What am I doing wrong?


回答1:


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

should something like this (untested):

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

i'm assuming the code is written this way (with global variables) for illustrative purposes and so i will ignore the other issues with the code sample that are likely not present in your real code, such as the property in your controller needing to be a computed.alias instead of direct assignment etc.



来源:https://stackoverflow.com/questions/48586922/cant-access-embers-class-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!