Ember.js中不使用Ember Data 建立模型的例子

來源:互聯網
上載者:User

Note: 本文基於 Ember.js 1.4.0 版本

1.不喜歡它
2.它還不穩定
3.後端開發的 RESTful3 API 風格不夠正,Ember Data 不適用
4.其他
當然,不用它並不會怎樣,因為我們還有許多輕量的替代品4,要是這些也都不喜歡,我們還可以手寫5 ajax 來建立 Ember.js 的模型部分6。

 代碼如下 複製代碼

window.App = Ember.Application.create(); // 建立 App 執行個體

App.Router.map(function() {
  this.route('person');
});

App.Model = Ember.Object.extend({}); // 定義一個 Model 類,所有 Model 都繼承自它

App.Person = App.Model.extend({
  firstName: null,
  lastName: null,
  age: null,
  gender: null
}); // 定義一個 Person 類

// 假定取得所有 person 的 api 介面為 http://www.111cn.net // 返回的資料結構是 {"people": [{"firstName": "Sam", "lastName": "Chen", "age": 18, "gender": "male"},{"firstName": "Jane", "lastName": "White", "age": 18, "gender": "female"}]}

接下來用 reopenClass7 給 Person 類增加一個方法,這個方法用於返回所有的 Person 執行個體:

 代碼如下 複製代碼

App.Person.reopenClass({
  findAll: function() {
    return $.get('http://www.111cn.net").then(
      function(response) {
        return response.people.map(function(person) { // map 是 JavaScript 的方法
          return App.Person.create(person);
        });
      }
    );
  }
});

這樣,在 Route 裡我們就可以設定 Model 了:

 代碼如下 複製代碼
App.PersonRoute = Ember.Route.extend({
  model: function() {
    return App.Person.findAll();
  },
  setupController: function(controller, model) {
    controller.set('model', model);
    // 也可以寫成 controller.set('content', model)
  }
});

之後可以在 Handlebars.js 模板裡使用模型資料了8:

 代碼如下 複製代碼

<table class=table>
<thead>
  <tr>
    <th>姓名</th>
    <th>年齡</th>
    <th>性別</th>
  </tr>
</thead>
<tbody>
{{#each}}
  <tr>
    <td>{{firstName}} {{lastName}}</td>
    <td>{{age}}</td>
    <td>{{gender}}</td>
  </tr>
{{/each}}
</tbody>
</table>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.