Code:
<!DOCTYPE html>
<html>
<head>
<title>Contacts</title>
<link href="lib/touch/resources/css-debug/sencha-touch.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="lib/touch/sencha-touch-all-debug.js"></script>
<script type="text/javascript">
Ext.define('Cart', {
extend: 'Ext.data.Model',
config: {
fields: [
{name: 'id', type: 'string'},
{name: 'created', type: 'date'},
{name: 'status', type: 'boolean'}
],
idProperty: 'id',
identifier: {
type: 'uuid'
},
associations: [
{
type: 'hasMany',
model: 'Product',
associationKey: 'products',
foreignKey: 'cart_id',
name: 'products',
autoLoad: true,
store: {
model: 'Product',
proxy: {
type: 'localstorage',
id: 'products'
}
}
}
]
}
});
Ext.define('Product', {
extend: 'Ext.data.Model',
config: {
fields: [
{name: 'product_id', type: 'string'},
{name: 'quantity', type: 'integer'},
{name: 'cart_id', type: 'string'},
],
// DONT SET OR DIFFERENT CARTS CANT HAVE THE SAME PRODUCT ID's
//idProperty: 'product_id',
identifier: {
type: 'uuid'
},
belongsTo: 'Cart'
}
});
Ext.define('Cartstore', {
extend: 'Ext.data.Store',
config: {
model: 'Cart',
proxy: {
type: 'localstorage',
id: 'carts'
}
}
});
Ext.application({
name: 'app',
launch: function()
{
// create the store
cart = Ext.create('Cartstore');
// load saved data from localstorage
cart.load();
// manually load associated products for each cart from localstorage
cart.each(function(record){
record.products().load();
});
// you can see the full object with all related data is in there
console.log(cart);
// create a new cart
var newCart = Ext.create('Cart', {
'created': new Date(),
'status': true
});
// PROBLEM: this new cart has ALL existing products put into it automatically....
console.log(newCart.products());
// add some products
newCart.products().add(Ext.create('Product', {
'product_id': 10,
'quantity': 1
}));
newCart.products().add(Ext.create('Product', {
'product_id': 25,
'quantity': 3
}));
// this contains the new cart with all the existing products, and all the new products
console.log(newCart);
// add the new cart to the store
cart.add(newCart);
// save cart to local storage
cart.sync();
// manually save the products to localstorage
newCart.products().sync();
// store will have old and newly added carts but newest cart will have all products associated with it
console.log(cart);
}
});
</script>
</head>
<body>
</body>
</html>