Ember.js MutableArray pushObject() 方法
Ember.js 是一款开源的 JavaScript 框架,用于开发基于模型-视图-控制器(MVC)架构的大型客户端Web应用程序。Ember.js是最广泛使用的前端应用程序框架之一,它旨在加快开发速度并提高生产力。目前,许多网站都在使用Ember.js,包括Square,Discourse,Groupon,LinkedIn,Live Nation,Twitch和Chipotle等。
pushObject() 方法用于将对象推入数组中。
语法:
pushObject(obj)
参数:
- obj (Object): 要推送的对象
返回值: 作为参数传递的对象
要运行以下示例,您需要拥有一个 Ember 项目。要创建一个项目,首先需要安装 ember-cli。在终端中编写以下代码:
npm install ember-cli
现在你可以通过输入以下代码来创建项目:
ember new <project-name> --lang en
要启动服务器,请输入:
ember serve
示例1: 输入以下代码以生成此示例的路径:
app/routes/notepad.js
import Route from '@ember/routing/route';
export default class NotepadRoute extends Route {
item;
items = ['Bread', 'Facewash'];
model() {
return this.items;
}
setupController(controller, model) {
this._super(controller, model);
controller.set('items', this.items);
}
}
app/controllers/notepad.js
import Ember from 'ember';
import { pushObject } from '@ember/array';
export default Ember.Controller.extend({
actions: {
addItem(item) {
console.log(item);
this.items.pushObject(item);
}
}
})
app/template/notepad.hbs
{{page-title "Notepad"}}
<h2>Your Items</h2>
<div>
<label>Enter Item: </label>
{{input value=this.item}}
</div>
<div>
<input type="button" id="add-item"
value="Add Item" {{action 'addItem' this.item}}/>
</div>
<br/><br/>
<ul>
{{#each @model as |i|}}
<li>{{i}}</li>
{{/each}}
</ul>
{{outlet}}
输出: 访问 localhost:4200/notepad 查看输出结果
示例2: 输入以下代码来生成此示例的路由:
ember generate route languages
app/routes/languages.js
import Route from '@ember/routing/route';
import { classify, w } from '@ember/string';
import { pushObject } 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();
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/4.4/classes/MutableArray/methods