Upgrade to ExtJS 4.0.2 - Released 06/09/2011
[extjs.git] / docs / guides / data / examples / lazy_associations / app.js
1 /**
2  * @example Lazy Associations
3  *
4  * This example demonstrates lazy loading of a {@link Ext.data.Model}'s associations only when requested.
5  * a `User` model is loaded, then a separate request is made for the `User`'s associated `Post`s
6  * See console for output.
7  */
8
9 // define the User model
10 Ext.define('User', {
11     extend: 'Ext.data.Model',
12     fields: ['id', 'name', 'age', 'gender'],
13
14     proxy: {
15         type: 'rest',
16         url : 'data/users',
17         reader: {
18             type: 'json',
19             root: 'users'
20         }
21     },
22
23     hasMany: 'Post' // shorthand for {model: 'Post', name: 'posts'}
24 });
25
26 //define the Post model
27 Ext.define('Post', {
28     extend: 'Ext.data.Model',
29     fields: ['id', 'user_id', 'title', 'body'],
30
31     proxy: {
32         type: 'rest',
33         url : 'data/posts',
34         reader: {
35             type: 'json',
36             root: 'posts'
37         }
38     },
39
40     belongsTo: 'User',
41     hasMany: {model: 'Comment', name: 'comments'}
42 });
43
44 //define the Comment model
45 Ext.define('Comment', {
46     extend: 'Ext.data.Model',
47     fields: ['id', 'post_id', 'name', 'message'],
48
49     belongsTo: 'Post'
50 });
51
52 Ext.require('Ext.data.Store');
53 Ext.onReady(function() {
54     // Loads User with ID 1 User's Proxy
55     User.load(1, {
56         success: function(user) {
57             console.log("User: " + user.get('name'));
58
59             // Loads posts for user 1 using Post's Proxy
60             user.posts().load({
61                 callback: function(posts, operation) {
62                     Ext.each(posts, function(post) {
63                         console.log("Comments for post: " + post.get('title'));
64
65                         post.comments().each(function(comment) {
66                             console.log(comment.get('message'));
67                         });
68                     });
69                 }
70             });
71         }
72     });
73 });
74