/models/shopCart/Collection.js
JavaScript | 46 lines | 43 code | 3 blank | 0 comment | 5 complexity | c53b7d481d48b5e1746e5dce19585346 MD5 | raw file
- define(
- [
- 'models/shopCart/Model',
- 'models/productList/productList'
- ],
- function(Model, shopListProducts) {
- return Backbone.Collection.extend({
- initialize: function(){
- var collection = this;
- collection
- .on('add change remove', function(){
- collection.sync();
- })
- },
- model: Model,
- url: '/shopCart/shopCart.json',
- addProduct: function(productId){
- var product = this.get(productId);
- if (product){
- product.set('amount', product.get('amount') + 1);
- } else {
- product = shopListProducts.get(productId);
- this.push(product.toJSON());
- }
- },
- removeProduct: function(productId){
- var product = this.get(productId);
- if (product.get('amount') <= 1){
- this.remove(product);
- } else {
- product.set('amount', product.get('amount') - 1);
- }
- },
- sync: function(){
- var collection = this;
- $.get(collection.url, collection.toJSON(), function(res){
- if (res.success) {
- window.localStorage.setItem('shopCartData', JSON.stringify(collection.toJSON()));
- }
- });
- }
- });
- });