日々精進

新しく学んだことを書き留めていきます

MVC Architectureその4

Saving data with the Model

Ext.define('AM.controller.Users', {
    init: function() {
        this.control({
            'viewport > userlist': {
                itemdblclick: this.editUser
            },
            'useredit button[action=save]': {
                click: this.updateUser
            }
        });
    },

    updateUser: function(button) {
        var win    = button.up('window'),//upメソッドでDOMツリーの親への参照を取れる
            form   = win.down('form'),//downはupの逆
            record = form.getRecord(),//record は変更前のModelっぽい
            values = form.getValues();//valuesは変更後のModel?

        record.set(values);//変更後の値に更新
        win.close();
    }
});

Storeのロジックを変更してデータをAjaxで読み込むようにするよ。

Ext.define('AM.store.Users', {
    extend: 'Ext.data.Store',
    model: 'AM.model.User',
    autoLoad: true,

//proxyを使うとAjax,local storage, JSONPなどを使ってデータを取得、送信できる
    proxy: {
        type: 'ajax',
        api: {//GETとPOSTで違うURLを指定出来る
            read: 'data/users.json',
            update: 'data/updateUsers.json'
        },
        reader: {//readerがデータをModelオブジェクトに変換する
            type: 'json',
            root: 'users',//Modelオブジェクトの配列をusersに代入する
            successProperty: 'success'//リクエスト成功時にTrueになるプロパティを指定してる。JSONのお作法的にリクエスト成功時にはsuccessなどの名前のプロパティにTrueを入れて返すようになっているらしい。
        }
    }
});

あとはコントローラのupdateUserメソッドAjaxリクエストを送信するコードを追加すればOK

updateUser: function(button) {
    var win    = button.up('window'),
        form   = win.down('form'),
        record = form.getRecord(),
        values = form.getValues();

    record.set(values);
    win.close();
    this.getUsersStore().sync();//Storeクラスの名前から自動的にgetUsersStoreが生成されるっぽい。
}