Ember 設(shè)置記錄到Store

2018-01-06 18:00 更新

EmberStore就像一個緩存池,用戶提交的數(shù)據(jù)以及從服務器獲取的數(shù)據(jù)會首先保存到Store。如果用戶再次請求相同的數(shù)據(jù)會直接從Store中獲取,而不是發(fā)送HTTP請求去服務器獲取。

當數(shù)據(jù)發(fā)生變化,數(shù)據(jù)首先更新到Store中,Store會理解更新到其他頁面。所以當你改變Store中的數(shù)據(jù)時,會立即反應出來,比如上一篇更新記錄小結(jié),當你修改article的數(shù)據(jù)時會立即反應到頁面上。

1,push()方法

你可以調(diào)用push()方法一次性把多條數(shù)據(jù)保存到Store中。比如下面的代碼:

  1. // app/routes/application.js
  2. import Ember from 'ember';
  3. export default Ember.Route.extend({
  4. model: function() {
  5. this.store.push({
  6. data: [
  7. {
  8. id: 1,
  9. type: 'album',
  10. attributes: { // 設(shè)置model屬性值
  11. title: 'Fewer Moving Parts',
  12. artist: 'David Bazan'
  13. songCount: 10
  14. },
  15. relationships: {} // 設(shè)置兩個model的關(guān)聯(lián)關(guān)系
  16. },
  17. {
  18. id: 2,
  19. type: 'album',
  20. attributes: { // 設(shè)置model屬性值
  21. title: 'Calgary b/w I Can\'t Make You Love Me/Nick Of Time',
  22. artist: 'Bon Iver',
  23. songCount: 2
  24. },
  25. relationships: {} // 設(shè)置兩個model的關(guān)聯(lián)關(guān)系
  26. }
  27. ]
  28. });
  29. }
  30. });

注意type屬性值必須是模型的屬性名字。attributes哈希里的屬性值與模型里的屬性對應。

本篇不是很重要,就簡單提一提,如有興趣請看Pushing Records Into The Store的詳細介紹。


博文完整代碼放在Github(博文經(jīng)過多次修改,博文上的代碼與github代碼可能有出入,不過影響不大?。?,如果你覺得博文對你有點用,請在github項目上給我點個star吧。您的肯定對我來說是最大的動力?。?/p>

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號