I try to increment a key value when saving data to localStorage. I know I can do that through closures but I'm fresh in JS and don't know how I can do this.
(function() {
window.onload = function() {
document.getElementById('buttonCreate').onclick = function() {
var topicValue = document.getElementById("create-topic").value;
var statusValue = document.getElementById("create-status").value;
var descriptionValue = document.getElementById("create-description").value;
var storage = new Storage();
var ticket = {
topic: topicValue,
status: statusValue,
description: descriptionValue
};
storage.set("Item", ticket);
}
}
})();
function Storage() {
this._ITEMS_DESCRIPTOR = 'items';
}
Storage.prototype.get = function() {
var fromStorage = localStorage.getItem(this._ITEMS_DESCRIPTOR);
return fromStorage ? JSON.parse(fromStorage) : [];
};
Storage.prototype.set = function(key, items) {
localStorage.setItem(key, JSON.stringify(items));
};
Related
I'm creating a kanban board and got stuck in deleting objects from local storage. I've 3 arrays for three kanban columns and they are stored with different keys. I need to delete certain card on click and update the array in local storage.
I already can restore the items and delete the markup on click, but it's still in local storage.
Here's my working code:
var saveToStorage = function (data, key) {
var dataString = JSON.stringify(data);
localStorage.setItem(key, dataString);
};
var getFromStorage = function (key) {
var dataString = localStorage.getItem(key);
return JSON.parse(dataString);
};
var deleteFromList = function (task, list) {
for (var i in list) {
var currentTask = list[i];
if (tasksAreEqual(currentTask, task)){
list.splice(i, 1);
}
}
};
var tasksAreEqual = function (task1, task2) {
var task1Str = JSON.stringify(task1);
var task2Str = JSON.stringify(task2);
return task1Str === task2Str;
};
var createCard = function (task) {
var card = $("<div class = \"card\">");
var cardBody = $("<div class=\"card-body\">");
var cardHeader = $("<div class=\"d-flex justify-content-between align-items-start\">");
var cardText = $("<p class=\"card-text\">").text(task.message);
var btnRemove = $("<button type='button' id='remove' class='btn btn-outline-danger'>").text("x");
var btnNext = $("<button type='button' id='next' class='btn btn-outline-success'>").text("Next =>");
cardHeader.append(cardText, btnRemove);
cardBody.append(cardHeader, btnNext);
card.append(cardBody)
btnRemove.on("click", function(e) {
e.preventDefault();
card.remove();
});
$("#todo").append(card);
};
var todoList = getFromStorage("todo") || [];
var progressList = getFromStorage("progress") || [];
var doneList = getFromStorage("done") || [];
var btnAdd = $("#add-btn");
btnAdd.on("click", function () {
var taskMsg = $("#task-msg").val();
var task = {
message: taskMsg
};
createCard(task);
todoList.push(task);
saveToStorage(todoList, "todo");
});
$(function() {
var todoArr = getFromStorage("todo");
for (var i of todoArr) {
var task = i;
createCard(task);
}
});
Save the list to localStorage when task removed
// added "return list;"
var deleteFromList = function(task, list) {
for (var i in list) {
if (tasksAreEqual(list[i], task)) {
list.splice(i, 1);
}
}
return list;
};
btnRemove.on("click", function(e) {
e.preventDefault();
todoList = deleteFromList(task, todoList);
localStorage.setItem('todo', JSON.stringify(todoList))
card.remove();
});
$(function() {
var todoArr = getFromStorage("todo");
// prevent the error 'TypeError: todoArr is null'
if (!todoArr) return;
for (var i of todoArr) {
var task = i;
createCard(task);
}
});
someone have any idea how i should modify the payment-lines in the POS,I want to add a type of credit card(like a many2one, I did it) but every time I add a line my option change to the first and also when the order is finished not save the value in pos.order -> statement_id.
enter image description here
here is my code:
function POS_CashRegister (instance, local) {
var pos = instance.point_of_sale;
var _t = instance.web._t;
var QWeb = instance.web.qweb;
var round_pr = instance.web.round_precision
const ParentOrder = pos.Order;
pos.PosModel.prototype.models.push({ //loaded model
model: 'pos.credit.card',
fields: ['id', 'name'],
domain: [['pos_active','=',true]],
loaded: function(self,credit_cards){ //pass parameters
self.credit_cards = credit_cards;
},
});
pos.PaymentScreenWidget = pos.PaymentScreenWidget.extend({
validate_order: function(options) {
var self = this;
var currentOrder = self.pos.get('selectedOrder');
var plines = currentOrder.get('paymentLines').models;
for (var i = 0; i < plines.length; i++) {
if(plines[i].cashregister.journal_id[1] === 'Tarjeta de Credito (PEN)')
{
var value = plines[i].node.firstElementChild.nextElementSibling.nextElementSibling.firstElementChild.value;
plines[i].set_credit_card(parseInt(value));
//console.log(plines[i].node.firstElementChild.nextElementSibling.nextElementSibling.firstElementChild.value);
//plines[i].node
}
}
console.log(currentOrder);
self._super(options);
},
render_paymentline: function (line) {
var self = this;
if(line.cashregister.journal_id[1] !== 'Tarjeta de Credito (PEN)'){
if (line.cashregister.currency[1] !== 'USD') {
return this._super(line);
} else {
var el_html = openerp.qweb.render('Paymentline', {widget: this, line: line});
el_html = _.str.trim(el_html);
var el_node = document.createElement('tbody');
el_node.innerHTML = el_html;
el_node = el_node.childNodes[0];
el_node.line = line;
el_node.querySelector('.paymentline-delete')
.addEventListener('click', this.line_delete_handler);
el_node.addEventListener('click', this.line_click_handler);
var sourceInput = el_node.querySelector('.source-input');
var convertedInput = el_node.querySelector('.converted-input');
sourceInput.addEventListener('keyup', function (event) {
el_node.line.set_usd_amount(event.target.value);
convertedInput.value = el_node.line.get_amount_str();
});
line.node = el_node;
return el_node;
}
}else {
return this._super(line);
}
},
});
pos.Paymentline = pos.Paymentline.extend({
initialize: function(attributes, options) {
this.amount = 0;
this.cashregister = options.cashregister;
this.name = this.cashregister.journal_id[1];
this.selected = false;
this.credit_card = false;
this.pos = options.pos;
},
set_credit_card: function(value){
this.credit_card = value;
this.trigger('change:credit_card',this);
},
get_credit_card: function(){
return this.credit_card;
},
export_as_JSON: function(){
return {
name: instance.web.datetime_to_str(new Date()),
statement_id: this.cashregister.id,
account_id: this.cashregister.account_id[0],
journal_id: this.cashregister.journal_id[0],
amount: this.get_amount(),
credit_card_id: this.get_credit_card(),
};
},
});
}
any suggestions?
You can create 2 journals here too. One for visa and another for master If you don't want that drop down there. Another way is you have to store selected option in a variable and then print that variable in front.
To store selected option initially assigned ids to each values of option and after then while validating order you can get that id of that field and from that id you can get your value. By this way also you can do that.
I want to increment my i value to save different value to local storage. But i always = 0, what can I do to change this behavior?
(function() {
var i = 0;
var storage = new Storage();
window.onload = function() {
document.getElementById('buttonCreate').onclick = function() {
var topicValue = document.getElementById("create-topic").value;
var statusValue = document.getElementById("create-status").value;
var descriptionValue = document.getElementById("create-description").value;
var ticket = {
topic: topicValue,
status: statusValue,
description: descriptionValue
};
storage.set("task-"+i, ticket);
i++;
}
}
})();
function Storage() {
this._ITEMS_DESCRIPTOR = 'items';
}
Storage.prototype.get = function() {
var fromStorage = localStorage.getItem(this._ITEMS_DESCRIPTOR);
return fromStorage ? JSON.parse(fromStorage) : [];
};
Storage.prototype.set = function(key, items) {
localStorage.setItem(key, JSON.stringify(items));
};
Declare the var i = 0 outside of the function. Right now it is being reset to 0 every time to function is run.
I need to increment key value when I'm saving data to localstorage because when I click button key is same for all records and record just update,doesn't creating new. I know I can do this with closures bit I'm fresh in JS and dont know how to do it correct.
(function() {
window.onload = function() {
document.getElementById('buttonCreate').onclick = function() {
var topicValue = document.getElementById("create-topic").value;
var statusValue = document.getElementById("create-status").value;
var descriptionValue = document.getElementById("create-description").value;
var key = 0;
var storage = new Storage();
var ticket = {
topic: topicValue,
status: statusValue,
description: descriptionValue
};
storage.set(key, ticket);
return (function() {
key++;
return key;
}());
}
}
})();
function Storage() {
this._ITEMS_DESCRIPTOR = 'items';
}
Storage.prototype.get = function() {
var fromStorage = localStorage.getItem(this._ITEMS_DESCRIPTOR);
return fromStorage ? JSON.parse(fromStorage) : [];
};
Storage.prototype.set = function(key, items) {
localStorage.setItem(key, JSON.stringify(items));
};
You need declare the variable before the function, to save the value and add 1+.
(function() {
window.onload = function() {
var key = 0; //move var key to here
document.getElementById('buttonCreate').onclick = function() {
var topicValue = document.getElementById("create-topic").value;
var statusValue = document.getElementById("create-status").value;
var descriptionValue = document.getElementById("create-description").value;
// var key = 0; remove these line
var storage = new Storage();
var ticket = {
topic: topicValue,
status: statusValue,
description: descriptionValue
};
storage.set(key, ticket);
return (function() {
key++;
return key;
}());
}
}
})();
I have created a new variable, carBasket and foodBasket, and set them equal to the basketModule() function. They however are pointed to the same function when I want each of these two variables pointed to their own function. I am wondering what should I be doing to achieve this?
var basketModule = (function() {
var basket = [];
return {
addItem: function(values) {
basket.push(values);
},
getItemCount: function() {
return basket.length;
}
};
}());
carBasket = basketModule;
carBasket.addItem('Audi');
foodBasket = basketModule;
foodBasket.addItem('Ham');
foodBasket.getItemCount(); //outputs 2 instead of 1
You must call a function for each object in order to generate different variables for each one, e.g:
var basketModule = function() {
var basket = [];
return {
addItem: function(values) {
basket.push(values);
},
getItemCount: function() {
return basket.length;
}
};
};
var carBasket = basketModule(),
foodBasket = basketModule();
carBasket.addItem('Audi');
foodBasket.addItem('Ham');
foodBasket.getItemCount(); // 1
However, in order to reuse the methods for all instances, better use a constructor:
var BasketModule = function() {
this.basket = [];
};
BasketModule.prototype.addItem = function(values) {
this.basket.push(values);
};
BasketModule.prototype.getItemCount = function() {
return this.basket.length;
};
var carBasket = new BasketModule(),
foodBasket = new BasketModule();
carBasket.addItem('Audi');
foodBasket.addItem('Ham');
foodBasket.getItemCount(); // 1
You should consider trying this pattern instead:
var BasketModule = function() {
var basket = [];
return {
addItem: function(values) {
basket.push(values);
},
getItemCount: function() {
return basket.length;
}
};
};
carBasket = new BasketModule();
carBasket.addItem('Audi');
foodBasket = new BasketModule();
foodBasket.addItem('Ham');
jsfiddle: https://jsfiddle.net/nvsbjset/
This will create separate objects for each basket