LoginSignup
9
8

More than 5 years have passed since last update.

AlloyのModelでREST APIからデータを取得する

Last updated at Posted at 2014-04-10

Githubで公開されていたREST API用のAdapterを利用してREST APIからデータを取得します。

実装方法

Adapterを導入

PROJECT_DIRECTORY/app/asset/alloy/syncにrestapi.jsを配置する。

ModelにAdapterを設定する

Modelで導入したAdapterを使用するように設定します。adapterとURLのあたり。
jsを使っている方は読み替えてください。

user.coffee
exports.definition =
  config:
    columns:
      id: 'string'
      name: 'string'
    URL: 'http://localhost:8080/user'
    adapter:
      type: 'restapi'
      collection_name: 'user'
      idAttribute: 'id'
    extendModel: (Model) ->
      _.extends Model.prototype, () ->
      Model
    extendCollection: (Collection) ->
      _.extends Collection.prototype, () ->
      Collection

REST APIからCollectionを生成

適当なControllerでREST APIからデータを取得します。

hoge.coffee
users = Alloy.createCollection 'user'

users.fetch
  success: () ->
    users.forEach (user) ->
      Ti.API.info user.id
  error: () ->
    Ti.API.info 'error'

困ったこと

ModelのなかでAlloy.CFGからリソースのurlを取ろうとしたんだけど取得できず。Alloy = requre 'Alloy'したらいける。
ModelではグローバルにAlloyが注入されてないんですね。

9
8
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
9
8