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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.