May 09, 2021 Ember.js Reference documents
The previous article introduced the query method, this article introduces the new, updated, delete the record method. T
he sample code for this article was created on the basis of the previous article.
For
consolidating firebase,
route
template
and templates, see the last article to add a controller:
ember g controller articles
Create a new record
createRecord()
method. F
or example, the following code creates
aritcle
record.
Modify the template and add a few
input
to the template to enter
article
information.
<div class="container">
<div class="row">
<div class="col-md-4 col-xs-4">
<ul class="list-group">
{{#each model as |item|}}
<li class="list-group-item">
{{#link-to 'articles.article' item.id}}
{{item.title}} -- <small>{{item.category}}</small>
{{/link-to}}
</li>
{{/each}}
</ul>
<div>
title:{{input value=title}}<br>
body: {{textarea value=body cols="80" rows="3"}}<br>
category: {{input value=category}}<br>
<button {{ action "saveItem"}}>保存</button>
<font color='red'>{{tipInfo}}</font>
</div>
</div>
<div class="col-md-8 col-xs-8">
{{outlet}}
</div>
</div>
</div>
The fields of the page correspond to the properties of this model
article
C
lick "Save" and submit to
controller
Here's the controller that gets the data to
controller
// app/controllers/articles.js
import Ember from 'ember';
export default Ember.Controller.extend({
actions: {
// 表单提交,保存数据到Store。Store会自动更新到firebase
saveItem: function() {
var title = this.get('title');
if ('undefined' === typeof(title) || '' === title.trim()) {
this.set('tipInfo', "title不能为空");
return ;
}
var body = this.get('body');
if ('undefined' === typeof(body) || '' === body.trim()) {
this.set('tipInfo', "body不能为空");
return ;
}
var category = this.get('category');
if ('undefined' === typeof(category) || '' === category.trim()) {
this.set('tipInfo', "category不能为空");
return ;
}
// 创建数据记录
var article = this.store.createRecord('article', {
title: title,
body: body,
category: category,
timestamp: new Date().getTime()
});
article.save(); //保存数据的到Store
// 清空页面的input输入框
this.set('title', "");
this.set('body', "");
this.set('category', "");
}
}
});
The first argument is the model name, which focuses on the
createRecord
method. T
he second argument is a hash, in which the model property value is always set. F
inally,
article.save()
method is called to save the data to the
Store
and then
Store
to firebase.
Here's how it works:
Enter the information and the data will appear immediately after the list "no form--java" when you click "Save". You can then click on the title to query the details, and the body's information will appear at the back of the page.
Through the example here I think you should know
createRecord()
method! B
ut what if there are two models that are associated with the method of saving?
A new model is added below.
ember g model users
Then add an association to the model.
// app/models/article.js
import DS from 'ember-data';
export default DS.Model.extend({
title: DS.attr('string'),
body: DS.attr('string'),
timestamp: DS.attr('number'),
category: DS.attr('string'),
author: DS.belongsTo('user') //关联user
});
// app/models/user.js
import DS from 'ember-data';
export default DS.Model.extend({
username: DS.attr('string'),
timestamp: DS.attr('number'),
articles: DS.hasMany('article') //关联article
});
Modifying
articles.hbs
adds an input author information field to the interface.
……省略其他代码
<div>
title:{{input value=title}}<br>
body: {{textarea value=body cols="80" rows="3"}}<br>
category: {{input value=category}}<br>
<br>
author: {{input value=username}}<br>
<button {{ action "saveItem"}}>保存</button>
<font color='red'>{{tipInfo}}</font>
</div>
……省略其他代码
Here's a look at how to set the correlation between the two models in
controller
There are two ways to set up, one
createRecord()
method and the other outside the method.
// app/controllers/articles.js
import Ember from 'ember';
export default Ember.Controller.extend({
actions: {
// 表单提交,保存数据到Store。Store会自动更新到firebase
saveItem: function() {
// 获取信息和校验代码省略……
// 创建user
var user = this.store.createRecord('user', {
username: username,
timestamp: new Date().getTime()
});
// 必须要执行这句代码,否则user数据不能保存到Store,
// 否则article通过user的id查找不到user
user.save();
// 创建article
var article = this.store.createRecord('article', {
title: title,
body: body,
category: category,
timestamp: new Date().getTime(),
author: user //设置关联
});
article.save(); //保存数据的到Store
// 清空页面的input输入框
this.set('title', "");
this.set('body', "");
this.set('category', "");
this.set('username', "");
}
}
});
Enter the information shown above, and click "Save" to see the following data association in the background of firebase.
Note: The association with these two data is maintained by
id
the data.
So what if I want to
user
information through
article
Get both directly in an object-oriented manner.
{{#each model as |item|}}
<li class="list-group-item">
{{#link-to 'articles.article' item.id}}
{{item.title}} -- <small>{{item.category}}</small> -- <small>{{item.author.username}}</small>
{{/link-to}}
</li>
{{/each}}
Watch out for
{{ item.author.username }}
M
uch like EL expression!! T
he association between the two models was mentioned earlier in two ways.
The following code is the second way:
// 其他代码省略……
// 创建article
var article = this.store.createRecord('article', {
title: title,
body: body,
category: category,
timestamp: new Date().getTime()
// ,
// author: user //设置关联
});
// 第二种设置关联关系方法,在外部手动调用set方法设置
article.set('author', user);
// 其他代码省略……
Run, re-enter the information, and the results are consistent. Y
ou can even call the
createRecord
method to set the relationship between the two models.
For example, the following snipp is a snipper:
var store = this.store; // 由于作用域问题,在createRecord方法内部不能使用this.store
var article = this.store.createRecord('article', {
title: title,
// ……
// ,
// author: store.findRecord('user', 1) //设置关联
});
// 第二种设置关联关系方法,在外部手动调用set方法设置
article.set('author', store.findRecord('user', 1));
This way, you can get the record directly and dynamically based on the user's id property value, and then set the association. The new introduction is over, followed by the update of the record.
Updates are very similar to new ones.
Take a look at the following snippppy code: First add the updated settings code to the template and modify the
articles/article.hbs
<h1>{{model.title}}</h1>
<div class = "body">
{{model.body}}
</div>
<div>
<br><hr>
更新测试<br>
title: {{input value=model.title}}<br>
body:<br> {{textarea value=model.body cols="80" rows="3"}}<br>
<button {{action 'updateArticleById' model.id}}>更新文章信息</button>
</div>
Add a controller,
controller
handles the modification information submitted by the sub-template.
ember g controller articles/article
// app/controllers/articles/article.js
import Ember from 'ember';
export default Ember.Controller.extend({
actions: {
// 根据文章id更新
updateArticleById: function(params) {
var title = this.get('model.title');
var body = this.get('model.body');
this.store.findRecord('article', params).then(function(art) {
art.set('title', title);
art.set('body', body);
// 保存更新的值到Store
art.save();
});
}
}
});
Select the data that needs to be updated on the left, and then modify the data that needs to be updated in the input box on the right, and during the modification process you can see that the modified information will immediately be reflected on the interface, because Ember automatically updates the data in the Store (remember the observer you said a long time ago?). )。
If you don't click Update Article Information to submit, the information you modify won't be updated to firebase. The page refreshes as it is, and if you click update article information data, the updated information will be submitted to firebase.
Because
save
findRecord
method returns a value that
promises
object, you can also handle error situations.
For example, the following code:
var user = this.store.createRecord('user', {
// ……
});
user.save().then(function(fulfill) {
// 保存成功
}).catch(function(error) {
// 保存失败
});
this.store.findRecord('article', params).then(function(art) {
// ……
}).catch(function(error) {
// 出错处理代码
});
Specific code I will not demonstrate, please readers write their own tests! !
Now that there is a new addition then there will usually be deletion. The deletion of records is very similar to modification, which is to query out the data to be deleted first, and then perform the deletion.
// app/controllers/articles.js
import Ember from 'ember';
export default Ember.Controller.extend({
actions: {
// 表单提交,保存数据到Store。Store会自动更新到firebase
saveItem: function() {
// 省略
},
// 根据id属性值删除数据
delById : function(params) {
// 任意获取一个作为判断表单输入值
if (params && confirm("你确定要删除这条数据吗??")) {
// 执行删除
this.store.findRecord('article', params).then(function(art) {
art.destroyRecord();
alert('删除成功!');
}, function(error) {
alert('删除失败!');
});
} else {
return;
}
}
}
});
Modify the template that displays the data, add the delete button, and pass the
id
data to
controller
<div class="container">
<div class="row">
<div class="col-md-4 col-xs-4">
<ul class="list-group">
{{#each model as |item|}}
<li class="list-group-item">
{{#link-to 'articles.article' item.id}}
{{item.title}} -- <small>{{item.category}}</small> -- <small>{{item.author.username}}</small>
{{/link-to}}
<button {{action 'delById' item.id}}>删除</button>
</li>
{{/each}}
</ul>
// ……省略其他代码
</div>
</div>
As shown above, click on the second data deletion button. P op-up prompt window, click "OK" after the successful deletion of data, and pop up "Delete successfully!" " , looking at the data in the firebase background, has indeed been deleted successfully. H owever, the user associated with this is not deleted, and under normal circumstances the associated user data should not be deleted. The end result is only one data:
At this end, the new, updated, delete methods are introduced. D
etailed demo examples have been given, and I believe that if you have personally practiced them in your own projects, it is easy to master these methods!
The full code of the blog post
is placed in Github
(the blog post has been modified several times, and the code on the blog post may be different from the github code, but the impact is small!). I
f you think the blog post is a bit useful to you, please give me a star on the
star
project.
Yours is definitely the biggest motivation for me!!