EmberJS 模型定義屬性

2018-01-03 19:35 更新

描述

DS.attr用于指定模型的屬性,它還使用可選的第二個(gè)參數(shù)作為散列:

語句

var attr = DS.attr;
DS.Model.extend({
    VarName: attr(),
    VarName: attr('DataType',{defaultValue: false}),
    VarName: attr()
});

例子

<!DOCTYPE html>
<html>
   <head>
      <title>Emberjs Defining Attributes</title>
      <!-- CDN's -->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js"></script>
      <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/ember.js/1.10.0/ember.min.js"></script>
      <script src="https://builds.emberjs.com/tags/v1.10.0-beta.3/ember-template-compiler.js"></script>
      <script src="https://builds.emberjs.com/release/ember.debug.js"></script>
      <script src="https://builds.emberjs.com/beta/ember-data.js"></script>
   </head>
   <body>
      <script type="text/x-handlebars" data-template-name="index">
         <h2>Players Names:</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í)行以下步驟,看看上面的代碼如何工作:

  • 將上面的代碼保存在model_defn_attr.html文件中

  • 在瀏覽器中打開此HTML文件。

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

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號