Ember.js MutableArray sortBy()方法
Ember.js 是一款基于模型-视图-控制器(MVC)架构用于开发大型客户端 Web 应用程序的开源 JavaScript 框架。Ember.js 是最广泛使用的前端应用程序框架之一。它旨在加快开发速度并提高生产力。目前,它被许多网站使用,包括Square、Discourse、Groupon、领英、现场国家、Twitch和Chipotle。
sortBy() 方法用于按指定键对数组进行排序。
语法:
sortBy( key )
参数:
- name(string): 要排序的名称。
返回值: 排序后的数组。
要运行以下示例,您需要有一个ember项目。要创建一个项目,您需要首先安装ember-cli。在终端中写入以下代码:
npm install ember-cli
现在,您可以通过输入以下一段代码来创建项目:
ember new <project-name> --lang en
开始服务器,输入:
ember serve
示例1
键入以下代码以生成此示例的路由:
ember generate route languages
app/routes/languages.js
import Route from '@ember/routing/route';
import { classify, w } from '@ember/string';
import { pushObject, sortBy } from '@ember/array';
export default class LanguagesRoute extends Route {
name =
`mandarin_Chinese spanish english Hindi
bengali Portuguese russian japanese
western_punjabi yueChinese`;
num = `929.0 474.7 372.9 343.9 233.7
232.4 154.0 125.3 92.7 85.2`;
languages = [];
initLanguages() {
this.languages = [];
this.name = w(this.name);
this.num = w(this.num);
for (let i = 0; i < this.name.length; i++) {
let obj = new Object();
obj['name'] = classify(this.name[i]);
obj['num'] = this.num[i];
this.languages.pushObject(obj);
}
}
model() {
this.initLanguages();
this.languages = this.languages.sortBy('name');
return this.languages;
}
}
app/template/languages.js
{{page-title "Languages"}}
<h2>Most Spoken Languages in the World</h2>
<table style="border: 2px solid black;padding: 30px;">
<tr>
<th>Language</th>
<th>Native Speakers (millions)</th>
</tr>
{{#each @model as |language|}}
<tr>
<td>{{language.name}}</td>
<td>{{language.num}}</td>
</tr>
{{/each}}
</table>
{{outlet}}
输出: 访问 localhost:4200/languages 查看输出结果
示例2
输入以下代码以生成此示例的路由:
ember generate route richest-people
app/routes/richest-people.js
import Route from '@ember/routing/route';
import { sortBy } from '@ember/array';
export default class RichestPeopleRoute extends Route {
richestPeople = [
{ 'name': 'mukesh ambani', 'net-worth': 90.7 },
{ 'name': 'jeff Bezos', 'net-worth': 148.1 },
{ 'name': 'Warren Buffet', 'net-worth': 99.3 },
{ 'name': 'Bill gates', 'net-worth': 104.7 },
{ 'name': 'elon Musk', 'net-worth': 253.4 },
{ 'name': 'gautam adani and family', 'net-worth': 115.8 },
{ 'name': 'Larry Page', 'net-worth': 93.4 },
{ 'name': 'larryEllison', 'net-worth': 103.3 },
{ 'name': 'sergeyBrin', 'net-worth': 89.9 },
{ 'name': 'bernard Arnault and family', 'net-worth': 157.1 },
];
model() {
this.richestPeople = this.richestPeople.sortBy('net-worth');
return this.richestPeople;
}
}
app/template/richest-people.hbs
{{page-title "Richest People"}}
<h2>Top 10 Richest Person in the World</h2>
<table style="border: 2px solid black;padding: 30px;">
<tr>
<th>Name</th>
<th>Net Worth (in Billion Dollars)</th>
</tr>
{{#each @model as |person|}}
<tr>
<td>{{person.name}}</td>
<td>{{person.net-worth}}</td>
</tr>
{{/each}}
</table>
{{outlet}}
输出: 访问localhost:4200/richest-people以查看输出
参考: https://api.emberjs.com/ember/4.4/classes/MutableArray/methods