当前位置: 首页 > 文档资料 > EmberJS 入门教程 >

将记录推入商店(Pushing Records Into The Store)

优质
小牛编辑
112浏览
2023-12-01

您可以将记录推送到商店的缓存中,而无需从应用程序请求记录。 如果记录在缓存中,只有当路由或控制器询问时,商店才能返回记录。

例子 (Example)

下面给出的示例显示了将记录推送到余烬火基中。 使用以下代码打开在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', '');
      }
   }
});

您可以在Ember Firebase上以JSON格式存储信息。 为此,您需要使用Firebase的网站创建帐户。 有关如何在应用程序中创建和配置Firebase的详细信息,请单击此link

输出 (Output)

运行ember服务器,您将获得输入框以输入值,如下面的屏幕截图所示 -

Ember.js将记录推送到商店

单击发送按钮后,它将显示用户输入的文本 -

Ember.js将记录推送到商店

现在打开您的firebase数据库,您将在Database部分下看到存储的值 -

Ember.js将记录推送到商店