EmberJS - 推送記錄



你可以在不從應用程式請求記錄的情況下將記錄推送到儲存器的快取中。如果僅當記錄在快取中時路由或控制器要求,儲存器即可返回記錄。

示例

下面給出的示例展示了將記錄推送到 firebase 中。使用以下程式碼開啟在 app/templates/ 下建立的 application.hbs 檔案:

<h2>Pushing Record into Store</h2>
<form>
   {{input type = "name" value = nameAddress placeholder = "Enter the text" 
      autofocus = "autofocus"}}
   //when user clicks the send button, the 'saveInvitation' action will get triggered
   <button {{action 'saveInvitation'}} >Send</button> 
</form>

{{#if responseMessage}}
   //display the response sessage after sending the text successfully
   {{responseMessage}}
{{/if}}
{{outlet}}

使用 invitation 名稱建立模型,該模型將在 app/models/ 下建立。開啟檔案,幷包括以下程式碼:

import DS from 'ember-data';

export default DS.Model.extend ({
   //specifying attribute using 'attr()' method
   name: DS.attr('string')
});

接下來,建立一個名稱為 application 的控制器,該控制器將在 app/controllers/ 中建立。開啟檔案,並新增以下程式碼:

import Ember from 'ember';

export default Ember.Controller.extend ({
   headerMessage: 'Coming Soon',
   //displays the response message after sending record to store
   responseMessage: '',
   nameAddress: '',

   actions: {
      //this action name which fires when user clicks send button
      saveInvitation() {
         const name = this.get('nameAddress');
         //create the records on the store by calling createRecord() method
         const newInvitation = this.store.createRecord('invitation', { name: name });
         newInvitation.save(); //call the save() method to persist the record to the backend
         this.set('responseMessage', `Thank you! We have saved your Name: ${this.get('nameAddress')}`);
         this.set('nameAddress', '');
      }
   }
});

你可以在 JSON 格式下儲存 Ember Firebase 上的資訊。為此,你需要使用 Firebase 的網站 建立帳戶。要了解有關如何在應用程式中建立和配置 Firebase 的更多資訊,請點選此 連結

輸出

執行 ember 服務端,你將獲得一個輸入框以輸入值,如下面的螢幕截圖中所示:

Ember.js Push Records into Store

單擊發送按鈕後,它將顯示使用者輸入的文字:

Ember.js Push Records into Store

現在開啟你的 Firebase 資料庫,你將看到儲存在 資料庫 部分下的值:

Ember.js Push Records into Store
emberjs_model.htm
廣告
© . All rights reserved.