Ember.js 字符串 underscore()方法
Ember.js是一个基于模型-视图-控制器(MVC)架构的开源JavaScript框架,用于开发大型客户端Web应用程序。Ember.js是最广泛使用的前端应用程序框架之一,因为它能加速开发并提高生产力。目前,它被许多网站使用,包括Square、Discourse、Groupon、Linked In、Live Nation、Twitch和Chipotle。
underscore()方法用于生成给定字符串的下划线版本。
语法:
underscore(str)
参数:
- str(string): 需要加下划线的字符串。
返回值: 加下划线后的字符串。
要运行以下示例,您需要有一个Ember项目。首先需要安装ember-cli,然后在终端中输入以下代码:
npm install ember-cli
现在您可以通过输入以下代码来创建项目:
ember new <project-name> --lang en
要启动服务器,请键入:
ember serve
示例1
输入以下代码以生成此示例的路由:
ember generate route richest-people
app/routes/richest-people.js
import Route from '@ember/routing/route';
import { underscore } from '@ember/string';
export default class RichestPeopleRoute extends Route {
richestPeople = [
'elon Musk',
'bernard Arnault and family',
'jeff Bezos',
'Bill gates',
'gautam adani and family',
'Larry Page',
'Warren Buffet',
'larry Ellison',
'mukesh ambani',
'sergey brin',
];
model() {
return this.richestPeople.map(underscore);
}
}
app/template/richest-people.hbs
{{page-title "Richest People"}}
<h2>Top 10 Richest People in the World</h2>
<ul>
{{#each @model as |rich-person|}}
<li>{{rich-person}}</li>
{{/each}}
</ul>
{{outlet}}
输出: 访问localhost:4200/richest-people查看输出结果
示例2
在此示例中,输入以下代码以生成路由:
ember generate route languages
app/routes/languages.js
import Route from '@ember/routing/route';
import { underscore } from '@ember/string';
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 = [];
for(let i = 0; i<this.name.length; i++) {
let obj = new Object();
obj['name'] = underscore(this.name[i]);
obj['num'] = this.num[i];
this.languages.push(obj);
}
}
model() {
this.initLanguages();
return this.languages;
}
}
app/template/languages.hbs
{{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 查看输出结果
参考链接: https://api.emberjs.com/ember/release/classes/String