LoginSignup
3
3

More than 5 years have passed since last update.

Ember.jsは現状データの保存、サーバとの通信の機能を提供していません。なので、サーバとのやり取りの処理は別途用意する必要があります。
今日は、ember-restという、Ember.ObjectにREST通信機能を追加するライブラリを紹介します。

ember-rest

ember-restを使ったrailsアプリケーションのサンプルが公開されています。このアプリケーションのコードを見ていきます。

ember_rest_example

このサンプルアプリケーションは、REST + JSONでサーバと通信し、オブジェクトのロード、セーブを行います。
サーバ側は /contacts というURLで、RESTインタフェースを実装しています。
JavaScript側でREST通信に使用する肝のコードは、以下の2つのオブジェクトです。

App.Contact = Ember.Resource.extend({
  resourceUrl:        '/contacts',
  resourceName:       'contact',
  resourceProperties: ['first_name', 'last_name'],

  validate: function() {
    if (this.get('first_name') === undefined || this.get('first_name') === '' ||
        this.get('last_name') === undefined  || this.get('last_name') === '') {
      return 'Contacts require a first and a last name.';
    }
  },

  fullName: Ember.computed(function() {
    return this.get('first_name') + ' ' + this.get('last_name');
  }).property('first_name', 'last_name')
});

App.contactsController = Ember.ResourceController.create({
  resourceType: App.Contact
});

Ember.Resource, Ember.ResourceControllerが、REST通信のための機能を提供しています。

↓全オブジェクトをロードしている箇所です。

  refreshListing: function() {
    App.contactsController.findAll();
  }

↓オブジェクトを保存している箇所です。

  submit: function(event) {
    var self = this;
    var contact = this.get("contact");

    event.preventDefault();

    contact.saveResource()
      .fail( function(e) {
        App.displayError(e);
      })
      .done( function() {
        var parentView = self.get("parentView");
        parentView.get("contact").duplicateProperties(contact);
        parentView.hideEdit();
      });
  }

Ember.Resource, Ember.ResourceControllerが提供している、REST通信のためのメソッドは以下のとおりです。

findResource

id指定でオブジェクトをロードします。 (GET xxx/id)

saveResource

オブジェクトを保存します。(POST xxx or PUT xxx/id)

destroyResource

オブジェクトを削除します。 (DELETE xxx/id)

findAll

全オブジェクトをロードします。

ember-restはシンプルな感じのライブラリですね。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3