EmberJS 定義模型

2018-01-03 19:32 更新

定義模型

在Emberjs,每個(gè)路線都有一個(gè)相關(guān)的模型。{{link-to}}或transitionTo()方法將一個(gè)參數(shù)作為實(shí)現(xiàn)路由模型鉤子的模型。該模型提高了應(yīng)用程序的魯棒性和性能。Emberjs使用 Ember Data 來(lái)處理服務(wù)器中存儲(chǔ)的數(shù)據(jù)。 ember.js 之后加入 ember-data.js

DS.Model.extend();

在上面的代碼中,我們?cè)趹?yīng)用程序的每個(gè)模型中創(chuàng)建一個(gè)DS.Model的子類。

例子

<!DOCTYPE html>
<html>
   <head>
      <title>Emberjs Defining Models</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="index">
         <h2>Players Name:</h2>
         {{#each person in controller}}
            <p>{{person.id}}: {{person.name}}</p>
         {{/each}}
      </script>

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

         //The store cache of all records available in an application
         App.Store = DS.Store.extend({
            //adapter translating requested records into the appropriate calls
            adapter: 'DS.FixtureAdapter'
         });

         App.ApplicationAdapter = DS.FixtureAdapter.extend();
            //defining model
         App.Person = DS.Model.extend({
            name: DS.attr('string')
         });

         App.IndexRoute = Ember.Route.extend({
            //index route
            model: function() {
               //return the person details
               return this.store.find('person');
            }
         });

         //attach fixtures(sample data) to the model's class
        App.Person.FIXTURES = [
           {id: 1, name: 'Virat'},
           {id: 2, name: 'Raina'},
           {id: 3, name: 'Dhoni'}
        ];
     </script>
  </body>
</html>

輸出

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

  • 將上述代碼保存在 defn_model.html 文件中

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

下表列出了屬性模型概念:

序號(hào)模型概念描述
1 定義屬性

它使用DS.attr指定模型的屬性。
2 定義關(guān)系

Ember.js具有內(nèi)置的關(guān)系,用于定義兩個(gè)模型之間的關(guān)系。
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

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

編程獅公眾號(hào)