티스토리 뷰

ExtJs의 data package는 application data를 조회/저장 기능을 담당하며, Model, Store, Ext.data.proxy.Proxy 클래스는 data 패키지의 핵심이다.
Data package overview

Models and Stores
data package의 핵심은 Ext.data.Model 클래스이다. Model은 어플리케이션의 테이터 타입을 표현한다. (예를 들면, e-commerce 어플리케이션의 사용자 상품, 거래 정보와 같은 데이터들) 가장 단순한 Model은 단지 해당 데이터들의 필드셋만 정의한다. 
Model architecture

간단한 모델을 생성해 보자!!!
Ext.define('User', {
    extend: 'Ext.data.Model',
    fields: [
        { name: 'id', type: 'int' },
        { name: 'name', type: 'string' }
    ]
});
모델은 일반적으로 Store와 함께 사용된다. Store는 기본적으로 Model 인스턴스의 컬렉션이다. Store를 설정하고 data를 읽어 오는 코드는 아래와 같다. 
Ext.create('Ext.data.Store', {
    model: 'User',
    proxy: {
        type: 'ajax',
        url : 'users.json',
        reader: 'json'
    },
    autoLoad: true
});
위의 코드에서 Store는 Ajax Proxy를 사용하도록 설정하였다. 이것은 설정된 url로 부터 데이터를 가져오며, 테이터를 decode하기 위해 Json Reader를 사용한다는 것을 의미한다. users.json url에서 리턴하는 json 데이터는 아래와 같다. 
{
    success: true,
    users: [
        { id: 1, name: 'Ed' },
        { id: 2, name: 'Tommy' }
    ]
}

Inline data

Store는 inline data로 부터 읽어 올 수 있다. 내부적으로 Store는 각각의 Object를 Model 객체로 변환한다.
Ext.create('Ext.data.Store', {
    model: 'User',
    data: [
        { firstName: 'Ed',    lastName: 'Spencer' },
        { firstName: 'Tommy', lastName: 'Maintz' },
        { firstName: 'Aaron', lastName: 'Conran' },
        { firstName: 'Jamie', lastName: 'Avins' }
    ]
});

Sorting and Grouping
Store들은 정렬, 필터링 그리고 그룹핑을 내부적으로 수행할 수 있다. 뿐만 아니라 원격 정렬, 필터링, 그룹핑 또한 지원한다.
Ext.create('Ext.data.Store', {
    model: 'User',

    sorters: ['name', 'id'],
    filters: {
        property: 'name',
        value   : 'Ed'
    },
    groupField: 'age',
    groupDir: 'DESC'
});

Proxies
Proxy는 Store에서 Model Data를 읽고/저장하기 위해 사용되어 진다. Proxy는 Client 와 Server 두개의 타입으로 나뉜다. 예를 들어 Client proxy들은 데이터들을 저장하기 위한 로컬 저장소를 포함하고 있다. (HTML5의 local storage 특성과 같은...) Server Proxy는 원격 서버로 부터의 데이터를 마샬링을 처리한다. (예를 들어 Ajax,  JsonP, Rest)
Proxy는 모델에 직접 정의할 수 있다. 
Ext.define('User', {
    extend: 'Ext.data.Model',
    fields: ['id', 'name', 'age', 'gender'],
    proxy: {
        type: 'rest',
        url : 'data/users',
        reader: {
            type: 'json',
            root: 'users'
        }
    }
});

// Uses the User Model's Proxy
Ext.create('Ext.data.Store', {
    model: 'User'
});
위의 방식은 두가지 이점이 있다. 첫번째로 User Model을 사용하는 모든 Sotre는 데이터를 로드하기 위해 Model의 Proxy를 사용한다. 그러므로 각각의 Store에 중복해서 proxy를 정의하지 않아도 된다. 두번째로 Store없이 바로 데이터를 로드하고 저장할 수 있게 된다.
// Gives us a reference to the User class
var User = Ext.ModelMgr.getModel('User');

var ed = Ext.create('User', {
    name: 'Ed Spencer',
    age : 25
});

// We can save Ed directly without having to add him to a Store first because we
// configured a RestProxy this will automatically send a POST request to the url /users
ed.save({
    success: function(ed) {
        console.log("Saved Ed! His ID is "+ ed.getId());
    }
});

// Load User 1 and do something with it (performs a GET request to /users/1)
User.load(1, {
    success: function(user) {
        console.log("Loaded user 1: " + user.get('name'));
    }
});
???

Associateions
Model은 Assocation API?와 함계 연계될 수 있다. 대부분의 어플리케이션은 다양한 Model들을 처리한다. 그리고 Model들은 대부분 연관되어 있다. 블로그 어플리케이션 같은 경우 User, Post, Comment 모델을 갖고 있을 것이며, 각각의 User는 Post를 생성할 것이고, 각각의 Post는 Comment가 달릴 것 이다. ExtJs에서는 이 와같은 관계를 다음과 같이 표현할 것 이다. 
Ext.define('User', {
    extend: 'Ext.data.Model',
    fields: ['id', 'name'],
    proxy: {
        type: 'rest',
        url : 'data/users',
        reader: {
            type: 'json',
            root: 'users'
        }
    },

    hasMany: 'Post' // shorthand for { model: 'Post', name: 'posts' }
});

Ext.define('Post', {
    extend: 'Ext.data.Model',
    fields: ['id', 'user_id', 'title', 'body'],

    proxy: {
        type: 'rest',
        url : 'data/posts',
        reader: {
            type: 'json',
            root: 'posts'
        }
    },
    belongsTo: 'User',
    hasMany: { model: 'Comment', name: 'comments' }
});

Ext.define('Comment', {
    extend: 'Ext.data.Model',
    fields: ['id', 'post_id', 'name', 'message'],

    belongsTo: 'Post'
});
이것은 어플리케이션에서 다양한 Model사이의 연관관계를 쉽게 표현할 수 있게 할 것이다. 각각의 모델들은 다양한 형태의 연과관계를 갖을 것이며, Model들은 임의의 순서로 정의될 것이다. 그러면 하나의 Model을 갖게 될 것이고 연관관계를 통해 쉽게 접근할 수 있을 것이다. 예를 들어 특정 User의 각 Post에 달린 모든 Comments들을 로그로 남기길 원한다면 아래와 같이 하면된다.
// Loads User with ID 1 and related posts and comments using User's Proxy
User.load(1, {
    success: function(user) {
        console.log("User: " + user.get('name'));

        user.posts().each(function(post) {
            console.log("Comments for post: " + post.get('title'));

            post.comments().each(function(comment) {
                console.log(comment.get('message'));
            });
        });
    }
});

Data Package관련 내용은 대충 여기까지 정리해야겠다... 계속 하다보니까 조금 지루하다. 추가 내용은 아래의 원문을 참조!!!

원문 :  http://docs.sencha.com/ext-js/4-0/#!/guide/data
댓글