app.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. // define the User model
  9. Ext.define('User', {
  10. extend: 'Ext.data.Model',
  11. fields: ['id', 'name', 'age', 'gender'],
  12. proxy: {
  13. type: 'rest',
  14. url : 'data/users',
  15. reader: {
  16. type: 'json',
  17. root: 'users'
  18. }
  19. },
  20. hasMany: 'Post' // shorthand for {model: 'Post', name: 'posts'}
  21. });
  22. //define the Post model
  23. Ext.define('Post', {
  24. extend: 'Ext.data.Model',
  25. fields: ['id', 'user_id', 'title', 'body'],
  26. proxy: {
  27. type: 'rest',
  28. url : 'data/posts',
  29. reader: {
  30. type: 'json',
  31. root: 'posts'
  32. }
  33. },
  34. belongsTo: 'User',
  35. hasMany: {model: 'Comment', name: 'comments'}
  36. });
  37. //define the Comment model
  38. Ext.define('Comment', {
  39. extend: 'Ext.data.Model',
  40. fields: ['id', 'post_id', 'name', 'message'],
  41. belongsTo: 'Post'
  42. });
  43. Ext.require('Ext.data.Store');
  44. Ext.onReady(function() {
  45. // Loads User with ID 1 User's Proxy
  46. User.load(1, {
  47. success: function(user) {
  48. console.log("User: " + user.get('name'));
  49. // Loads posts for user 1 using Post's Proxy
  50. user.posts().load({
  51. callback: function(posts, operation) {
  52. Ext.each(posts, function(post) {
  53. console.log("Comments for post: " + post.get('title'));
  54. post.comments().each(function(comment) {
  55. console.log(comment.get('message'));
  56. });
  57. });
  58. }
  59. });
  60. }
  61. });
  62. });