LoginSignup
1
0

More than 5 years have passed since last update.

Sencha Touch 2 で、controller から view へデータを渡す方法

Posted at

http://stackoverflow.com/questions/8391551/sencha-touch-2-mvc-how-to-pass-cache-data-between-views-and-controllers
にかかれているように、controller でビジネスロジックを持つようにし、view では表示のみを受け持つ方が良い。
その為、受け渡したい model のインスタンスを controller 側で生成してから、View を呼び出す方法が望ましい

たとえばこういう model があるとする

model/UserPicture.coffee
Ext.define("MyApp.model.UserPicture", {
  extend: "Ext.data.Model",
  config: {
    fields: [
      {
        name: "id",
        type: "int"
      }, {
        name: "login_id",
        type: "string"
      }, {
        name: "time",
        type: "string"
      }, {
        name: "description",
        type: "auto"
      }, {
        name: "picture",
        type: "auto"
      }
    ],
  }
});

このデータを http://hoge.com/fuga.json から取ってきて、以下の PictureListView に表示したい。

view/PictureListView
Ext.define "Ezuko.view.PictureListView",
  extend: "Ext.List"
  xtype: "picturelist"
  id: 'picturelist'
  config:
    itemTpl:[ '<img src="{picture}"/>',
              '<div>{description}</div>'].join('')

まずは app/store/ 以下に Proxy を定義した Store クラスを作成する。

store/UserPicture
Ext.define 'MyApp.store.UserPicture'
  extend: 'Ext.data.Store'
  config:
    model: 'MyApp.model.UserPicture',
    proxy:
      type: 'ajax'
      url: 'http://hoge.com/fuga.json'
      reader:
        type: 'json'
        rootProperty: "user_pictures"

fuga.json では、'user_pictures' 以下が UserPicture model に対応しているものとする。

この store を Controller で呼び出して、View に渡すには以下のようにする

controller/Main.coffee
Ext.define 'MyApp.controller.Main',
    extend: 'Ext.app.Controller'
    config:
      routes:
        'picture/index' : 'pictureIndex'
      models: ['UserPicture']
      stores: ['UserPicture']

    pictureIndex:() ->
      store = new MyApp.store.UserPicture()
      store.load (records, operation, success) ->
          view = new Ext.Container
            layout: 'card'
            items: [
              xtype:'picturelist'
              store: store
            ]
          Ezuko.Viewport.push(view);
        , scope: this
1
0
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
1
0