[英]Can't access Ember's class variable
How to properly pass a variable to an Ember's class? 如何正确地将变量传递给Ember的类?
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. this.get('companies')
是未定义的。 Why? 为什么? I'm passing companies
to AppModel.create
. 我正在将companies
传递给AppModel.create
。 What am I doing wrong? 我究竟做错了什么?
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. 我假设代码是用这种方式(带有全局变量)编写的,用于说明目的,因此我将忽略代码样本中可能在您的真实代码中不存在的其他问题,例如控制器中的属性需要别名代替直接分配等
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.