Ember.js MutableArray popObject() 方法
Ember.js是一个开源的JavaScript框架,用于开发基于模型-视图-控制器(MVC)架构的大型客户端Web应用程序。Ember.js是最广泛使用的前端应用程序框架之一。它旨在加快开发速度和提高生产力。目前,许多网站都在使用它,包括Square、Discourse、Groupon、Linked In、Live Nation、Twitch和Chipotle。
popObject()方法 用于从数组中弹出对象。
语法:
popObject()
返回值: 弹出的对象
若要运行以下示例,您需要具有一个 Ember 项目。要创建一个项目,首先需要安装 ember-cli。在终端中写入下面的代码:
npm install ember-cli
现在你可以通过输入以下代码来创建项目:
ember new <project-name> --lang en
要启动服务器,请输入:
ember serve
示例1: 输入以下代码以生成该示例的路线:
ember generate route notepad
app/routes/notepad.js
import Route from '@ember/routing/route';
export default class NotepadRoute extends Route {
items = ['Bread', 'Facewash', 'Egg', 'Pen', 'Medicine'];
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 { popObject } from '@ember/array';
export default Ember.Controller.extend({
actions: {
removeItem() {
if (this.items.length == 0)
alert('Item List is Empty');
this.items.popObject();
}
}
})
app/template/notepad.hbs
{{page-title "Notepad"}}
<h2>Your Items</h2>
<ul>
{{#each @model as |i|}}
<li>{{i}}</li>
{{/each}}
</ul>
<br/><br/>
<div>
<input type="button" id="remove-item"
value="Remove Item" {{action 'removeItem'}}/>
</div>
{{outlet}}
输出: 访问 localhost:4200/notepad 查看输出结果
示例2: 输入以下代码来生成此示例的路由:
ember generate route richest-people
app/routes/richest-people.js
import Route from '@ember/routing/route';
import { classify, w } 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'];
num = 10;
init() {
this.richestPeople = this.richestPeople.map(classify);
}
model() {
this.init();
return this.richestPeople;
}
setupController(controller, model) {
this._super(controller, model);
controller.set('num', this.num);
controller.set('richestPeople',this.richestPeople)
}
}
app/controllers/richest-people.js
import Ember from 'ember';
import { popObject } from '@ember/array';
export default Ember.Controller.extend({
actions: {
set(n) {
this.num = parseInt(n);
while (this.richestPeople.length > this.num) {
this.richestPeople.popObject();
}
}
}
})
app/template/richest-people.hbs
{{page-title "Richest People"}}
<div>
<label>Enter Value: </label>
{{input value=this.num}}
</div>
<div>
<input type="button" id="fetch"
value="Fetch" {{action 'set' this.num}}/>
</div>
<br/><br/>
<h2>Top {{this.num}} Richest People in the World</h2>
<ul>
{{#each @model as |rich-person|}}
<li>{{rich-person}}</li>
{{/each}}
</ul>
{{outlet}}
输出: 访问 localhost:4200/richest-people 查看输出
参考: https://api.emberjs.com/ember/4.4/classes/MutableArray/methods