15

任何人都可以请我指出 ExtJS 中关联的一个工作示例(与 hasMany 和 belongsTo)。请不要将我指向 Sencha 文档或任何与 Sencha 相关的示例,因为我几乎尝试了所有方法,但它们都不起作用......

4

1 回答 1

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": "user@example.com",
                    "body": "test comment"
                },
                {
                    "id":66,
                    "emailAddress": "user2@example.com",
                    "body": "another comment"
                }
            ]
        }
    ]
}
于 2013-05-11T01:41:45.100 回答