1. The first step in linking two Models together is to define them. Start by defining a
Book model:
Ext.define('Book', {
extend: 'Ext.data.Model',
fields: [{
name: 'Title',
type: 'string'
}, {
name: 'Publisher',
type: 'string'
}, {
name: 'ISBN',
type: 'string'
}, {
name: 'PublishDate',
type: 'date',
dateFormat: 'd-m-Y'
}, {
name: 'NumberOfPages',
type: 'int'
}, {
name: 'Read',
type: 'boolean'
}]
});
2. The second Model, Author, should be defined next:
Ext.define('Author', {
extend: 'Ext.data.Model',
fields: [{
name: 'Title',
type: 'string'
}, {
name: 'FirstName',
type: 'string'
}, {
name: 'LastName',
type: 'string'
}, {
name: 'book_id',
type: 'int'
}]
});
3. Add an association to the Book Model:
Ext.define('Book', {
...
associations: [{
type: 'hasMany',
model: 'Author',
name: 'authors'
}]
});
4. Now that we have defined the Book Model, we can create an instance of it containing
some data about this book:
var book = Ext.create('Book', {
Title: 'Ext JS 4 CookBook',
Publisher: 'Packt Publishing',
ISBN: '978-1-849516-86-0',
PublishDate: '01-01-2012',
NumberOfPages: 300,
Read: false
});
5. Run the book.authors() function, which returns a Store for the authors:
var authors = book.authors();
6. Add two authors to the Author Store. These authors will be linked to the book
through a foreign key book_id:
authors.add({
Title: 'Mr',
FirstName: 'Andrew',
LastName: 'Duncan'
}, {
Title: 'Mr',
FirstName: 'Stuart',
LastName: 'Ashworth'
});
7. Create a Store with a Book Model and load the provided books.json file:
var store = Ext.create('Ext.data.Store', {
model: 'Book',
autoLoad: true,
proxy: {
type: 'ajax',
url: 'books.json'
}
});
8. When the load event has been fired we will do some processing to ensure that the
data has been loaded into its respective Models:
store.on('load', function(){
var record = store.getAt(0);
console.log(record);
console.log(record.get('Title'));
var authors = record.getAssociatedData();
console.log(authors);
var author = record.authors().getAt(0);
console.log(author.get('FirstName'));
});
댓글 없음:
댓글 쓰기