2013-05-10 79 views
15

任何人都可以请我指出一个在ExtJS中关联的实例(hasMany和belongsTo)。请不要点我煎茶文档或与煎茶任何例子,因为我试过几乎所有的东西,但没有人的作品...协会在extjs 4.2中的示例:

回答

9

运行示例(打开你的浏览器控制台):

http://jsfiddle.net/4TSDu/52/

Ext.define('My.model.Author', { 
    extend:'Ext.data.Model', 
    fields:[ 
     'name' 
    ] 
}); 

Ext.define('My.model.Comment', { 
    extend:'Ext.data.Model', 
    fields:[ 
     'emailAddress', 
     'body' 
    ] 
}); 

Ext.define('My.model.BlogPost', { 
    extend:'Ext.data.Model', 
    fields:[ 
     'title', 
     'body' 
    ], 
    belongsTo:[ 
     { 
      name:'author', 
      instanceName:'author', 
      model:'My.model.Author', 
      getterName:'getAuthor', 
      setterName:'setAuthor', 
      associationKey:'author' 
     } 
    ], 
    hasMany:[ 
     { 
      name:'comments', 
      model:'My.model.Comment', 
      associationKey:'comments' 
     } 
    ], 
    proxy:{ 
     type:'ajax', 
     url:'https://dl.dropboxusercontent.com/u/1015920/Ext/blog-posts.json', 
     reader:{ 
      type:'json', 
      root:'data' 
     } 
    } 
}); 

My.model.BlogPost.load(1, { 

    success:function(record, operation){ 

     console.log(record.get('title')); // "some title" 

     console.log(record.getAuthor().get('name')); // "neil" 

     console.log(record.comments().getCount()); // 2 

    } 
}); 

在这里阅读更多:

http://extjs-tutorials.blogspot.ca/2012/05/extjs-belongsto-association-rules.html

http://extjs-tutorials.blogspot.ca/2012/05/extjs-hasmany-relationships-rules.html

使用的样品数据:

{ 
    "data": [ 
     { 
      "id": 1, 
      "title": "some title", 
      "body": "some body", 
      "author": {"id":1, "name": "neil"}, 
      "comments": [ 
       { 
        "id":55, 
        "emailAddress": "[email protected]", 
        "body": "test comment" 
       }, 
       { 
        "id":66, 
        "emailAddress": "[email protected]", 
        "body": "another comment" 
       } 
      ] 
     } 
    ] 
} 
+0

喜尼尔,对不起,在我的响应延迟。我试图运行这个,但无法在控制台中获得任何输出。我把整个代码放在一个onReady函数中,用你提到的数据创建了一个json文件。数据正在被抓取(检查萤火虫控制台),但它似乎并没有被称为成功功能。而且我无法看到您提供的jsFiddle中的任何控制台输出。你能不能让我知道,如果我在这里做错了什么... – CARTIC 2013-05-14 14:44:52

+0

测试/在铬,火狐和Safari的作品。我正在使用远程数据,因此无法在IE中工作(尽管可能在IE10中)。你正在使用? – 2013-05-14 17:59:21

+0

嗨尼尔,我试着用firefox 20.0.1,chrome 26.0和IE 8.我发现json文件本身并没有在jsFiddle中获取,这是由于防火墙和安全设置(公司策略)。有没有办法在JsFiddle中内联添加数据。另外,请让我知道,如果我试图从eclipse运行示例的方式是正确的(它在我以前的评论中)。在那里我能够获得json数据,但成功函数从未被调用过。我试图用firefox 20安装萤火虫... – CARTIC 2013-05-15 04:23:00