无法访问Ember的类变量 [英] Can't access Ember's class variable
问题描述
如何正确地将变量传递给Ember的类?
How to properly pass a variable to an Ember's class?
控制器:
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>
在浏览器控制台中上述操作的结果:
The result of the above in the browser console:
jquery.js:3827 Uncaught TypeError: Cannot read property 'sort' of undefined
this.get('companies')
未定义。为什么?我正在将公司
传递给 AppModel.create
。我在做什么错?
this.get('companies')
is undefined. Why? I'm passing companies
to 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);
});
}
});
我假设代码是以这种方式编写的(带有全局变量)用于说明目的,因此我将忽略代码示例中的其他问题可能不会出现在您的实际代码中,例如,控制器中的属性需要为Calculation.alias而不是直接分配等。
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.
这篇关于无法访问Ember的类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!