Ext.define('Book', {
extend: 'Ext.data.Model',
idProperty: 'BookID',
fields: [{
name: 'BookID',
type: 'int'
}, {
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'
}],
validations: [{
type: 'length',
field: 'Title',
min: 1
}, {
type: 'presence',
field: 'Publisher'
}]
});
2. Our next task is to define the Model's proxy. This will define how the Model will load
or save itself when asked to. We will use a simple AJAX proxy with a URL defined for
each of the four CRUD (Create, Read, Update, Delete) actions:
...
proxy: {
type: 'ajax',
api: {
read: 'bookRead.php',
create: 'bookCreate.php',
update: 'bookUpdate.php',
destroy: 'bookDestroy.php'
}
}
3. Now that we have a Proxy set up we can use the Book's static load method to call
the server and fetch a Book's data based on the ID passed in, as in our first example.
As the call is asynchronous we use a callback function to simply log the loaded model
instance once the AJAX call is complete:
Book.load(1, {
callback: function(book, operation){
console.log(book);
}
});
4. If we manually create a new Book model instance, and include a BookID in its data,
we can call the save method and see the bookUpdate.php file being called, with
the Book's data being posted to it:
var book = Ext.create('Book', {
BookID: 1,
Title: 'Ext JS 4 CookBook',
Publisher: 'Packt Publishing',
ISBN: '978-1-849516-86-0',
PublishDate: '01-01-2012',
NumberOfPages: 300,
Read: false
});
book.save();
5. Similarly, if we create a Book without a BookID and call the save method, the
bookCreate.php file with be called with the Book's data passed to it.
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
});
book.save();
6. Finally, we can delete a Book record by calling the destroy method of the Book
instance, which will cause an AJAX call to be made to the configured destroy URL:
var book = Ext.create('Book', {
BookID: 1,
Title: 'Ext JS 4 CookBook',
Publisher: 'Packt Publishing',
ISBN: '978-1-849516-86-0',
PublishDate: '01-01-2012',
NumberOfPages: 300,
Read: false
});
book.destroy();
댓글 없음:
댓글 쓰기