EmberJS 持久記錄

2018-01-03 14:08 更新

持久記錄

Ember.js記錄數(shù)據(jù)在每個(gè)實(shí)例的基礎(chǔ)上持久化。DS.Model對(duì)任何實(shí)例使用save()發(fā)出網(wǎng)絡(luò)請(qǐng)求。

store.createRecord('route', {
   //declare properties
   route.save();
});

在上面的代碼中,route.save()有助于記錄數(shù)據(jù)。

例子

<!DOCTYPE html>
<html>
   <head>
      <title>Emberjs Persisting Records</title>
      <!-- CDN's-->
      <script src="/attachements/w3c/handlebars.min.js"></script>
      <script src="/attachements/w3c/jquery-2.1.3.min.js"></script>
      <script src="/attachements/w3c/ember.min.js"></script>
      <script src="/attachements/w3c/ember-template-compiler.js"></script>
      <script src="/attachements/w3c/ember.debug.js"></script>
      <script src="/attachements/w3c/ember-data.js"></script>
   </head>
   <body>
      <script type="text/x-handlebars" data-template-name="fruits">
         <h1>Enter Fruit Names to Add</h1>
            {{input type="text" value=newTitle action="createFru"}}
            {{#each fru in model}}
               {{fru.title}}
            {{/each}}
      </script>

      <script type="text/javascript">
         Fruits = Ember.Application.create();

         Fruits.ApplicationAdapter = DS.FixtureAdapter.extend();

         Fruits.Router.map(function () {
            this.resource('fruits', { path: '/' });
         });

         Fruits.FruitsRoute = Ember.Route.extend({
            model: function () {
               return this.store.find('fru');
            }
         });

         Fruits.Fru = DS.Model.extend({
            //data model
            title: DS.attr('string')
         });

         //attach fixtures(sample data) to the model's class
         Fruits.Fru.FIXTURES = [{
            id: 1,
            title: 'Apple'
         }];

         Fruits.FruitsController = Ember.ArrayController.extend({
            actions: {
               createFru: function () {
                  // Get the fru title set by the "New Todo" text field
                  var title = this.get('newTitle');

                  // Create the new 'fru'(fruit) model
                  var fru = this.store.createRecord('fru', {
                  title: title
               });

               // Save the new model
                fru.save();
              }
            }
         });
      </script>
   </body>
</html>

輸出

讓我們執(zhí)行以下步驟,看看上面的代碼如何工作:

  • 將以上代碼保存在 persist_model.html 文件中

  • 在瀏覽器中打開(kāi)此HTML文件。

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

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)