JSFiddle - React, Tailwind, and code Playground
by dsbonev
JavaScript
YUI().use('model', 'json-stringify', function MVC(Y) {
var NAME = 'shopingCart',
Lang = Y.Lang;
Y.ShopingCart = Y.Base.create(NAME, Y.Model, [], {
addItem: function(item) {
this.getItems().push(item);
this.fire('itemAdd', {
data: {
item: item
}
});
return this;
},
getItems: function() {
return this.get('items');
},
removeItem: function(item) {
var items = this.getItems();
var index = items.indexOf(item);
if (index !== -1) {
items.splice(index, 1);
}
},
sync: function(action, options, callback) {
var data;
if (action === 'create') {
data = this.toJSON();
data.id = Y.Lang.now();
localStorage.setItem(data.id, Y.JSON.stringify(data));
callback(null, data);
return;
} else if (action === 'read') {
data = localStorage.getItem(this.get('id'));
if (data) {
callback(null, data);
} else {
callback('Model not found.');
}
return;
} else if (action === 'update') {
data = this.toJSON();
// Update the record in localStorage, then call the callback.
localStorage.setItem(this.get('id'), Y.JSON.stringify(data));
callback(null, data);
return;
} else if (action === 'delete') {
localStorage.removeItem(this.get('id'));
callback();
return;
} else {
callback('Invalid action');
}
}
}, {
ATTRS: {
items: {
value: [],
validator:...