Angular ngStorage Custom Objects - javascript

I am using ngStorage to store data. I made a custom objects called game and stored it. Its stored as a game but when i refresh the browser it comes back as an Object.
var games= $localStorage.games || {};
this.addGame = function(){
var newGame = new game("Game "+games.length);
$localStorage.games = newGame;
}
var game = function(title){
var title=title;
var player1;
var player2;
this.getTitle = function(){
return title;
}
this.setTitle = function(title){
this.title = title;
}
this.getPlayer1 = function(){
return player1;
}
this.setPlayer1 = function(player1){
this.player1 = player1;
}
this.getPlayer2 = function(){
return player2;
}
this.setPlayer1 = function(player1){
this.player2 = player2;
}
}
When a new game is added it's stored as a game in LocalStorage but when I refresh the bowser and tried to fetch games. It returns as an array of Objects not games.

You cannot store objects in localStorage. The hack is that you can store string and parse/unparse them like this.
var game = {
name: 'Super Metroid',
text: 'This is an awesome game!!!'
};
window.localStorage['game'] = JSON.stringify(game);
var superMetroid = JSON.parse(window.localStorage['game'] || '{}');

Related

Local Storage is overwritten instead of the new elements being added (JavaScript)

I want to storage an array of objects in local storage but I just can storage one object into the array. All the new objects are overwriting the previous one in index 0.
This is my JavaScript code:
class Track {
constructor (title, genre) {
this.title = title;
this.genre = genre;
this.id = new Date().getTime();
this.creation = new Date();
}
}
class TrackList {
constructor () {
this.tracks = [];
}
newTrack(track) {
this.tracks.push(track);
this.saveLocalStorage();
}
saveLocalStorage() {
localStorage.setItem('tracks', JSON.stringify(this.tracks));
}
}
const addSongForm = document.querySelector('.addSongForm');
addSongForm.addEventListener('submit', (e) => {
const songTitle = document.querySelector('.songTitle').value;
const songGenre = document.querySelector('.songGenre').value;
const newTrackForm = new Track(songTitle, songGenre);
const trackList = new TrackList();
trackList.newTrack(newTrackForm);
});
Thanks in advance!!
get the current content of the local storage first and then put the new objects into the array.
var currentTracks = localStorage.getItem('tracks');
localStorage.setItem('tracks', JSON.stringify(JSON.parse(currentTracks).concat(this.tracks)));
EDIT: if the current objects that has the same ID as the new object need to be replaced, the new array needs to be adjusted.
/**
* source : https://www.cnblogs.com/water-1/p/10780528.html
*/
function mergeArray(arr1,arr2){
var _arr = new Array();
for(var i=0;i<arr1.length;i++){
_arr.push(arr1[i]);
}
for(var i=0;i<arr2.length;i++){
var flag = true;
for(var j=0;j<arr1.length;j++){
if(arr2[i]['id']==arr1[j]['id']){
flag=false;
break;
}
}
if(flag){
_arr.push(arr2[i]);
}
}
return _arr;
}
var currentTracks = JSON.parse(localStorage.getItem('tracks'));
localStorage.put('tracks', mergeArray(this.tracks, currentTracks));

How to show popup error in Point of Sale in odoo 12

I want to restrict the user from adding more product to sell if the order is tag as booked order
I want to show popup error message when it is booked order and the user still click the product
here is my code
odoo.define('tw_pos_inherit_model.attemptInherit', function (require) {
"use strict";
var POSInheritmodel = require('point_of_sale.models');
var ajax = require('web.ajax');
var BarcodeParser = require('barcodes.BarcodeParser');
var PosDB = require('point_of_sale.DB');
var devices = require('point_of_sale.devices');
var concurrency = require('web.concurrency');
var config = require('web.config');
var core = require('web.core');
var field_utils = require('web.field_utils');
var rpc = require('web.rpc');
var session = require('web.session');
var time = require('web.time');
var utils = require('web.utils');
var gui = require('point_of_sale.gui');
var orderline_id = 1;
var QWeb = core.qweb;
var _t = core._t;
var Mutex = concurrency.Mutex;
var round_di = utils.round_decimals;
var round_pr = utils.round_precision;
var _super_order = POSInheritmodel.Order.prototype;
POSInheritmodel.Order = POSInheritmodel.Order.extend({
add_product: function(product, options){
var can_add = true;
var changes = this.pos.get_order();
var self = this;
try{
if(changes.selected_orderline.order.quotation_ref.book_order){
can_add= false;
}
}catch(err){}
if (can_add){
if(this._printed){
this.destroy();
return this.pos.get_order().add_product(product, options);
}
this.assert_editable();
options = options || {};
var attr = JSON.parse(JSON.stringify(product));
attr.pos = this.pos;
attr.order = this;
var line = new POSInheritmodel.Orderline({}, {pos: this.pos, order: this, product: product});
if(options.quantity !== undefined){
line.set_quantity(options.quantity);
}
if(options.price !== undefined){
line.set_unit_price(options.price);
}
//To substract from the unit price the included taxes mapped by the fiscal position
this.fix_tax_included_price(line);
if(options.discount !== undefined){
line.set_discount(options.discount);
}
if(options.discount_percentage !== undefined){
line.set_if_discount_percentage(options.discount_percentage);
}
if(options.discount_amount !== undefined){
line.set_if_discount_amount(options.discount_amount);
}
if(options.extras !== undefined){
for (var prop in options.extras) {
line[prop] = options.extras[prop];
}
}
var to_merge_orderline;
for (var i = 0; i < this.orderlines.length; i++) {
if(this.orderlines.at(i).can_be_merged_with(line) && options.merge !== false){
to_merge_orderline = this.orderlines.at(i);
}
}
if (to_merge_orderline){
to_merge_orderline.merge(line);
} else {
this.orderlines.add(line);
}
this.select_orderline(this.get_last_orderline());
if(line.has_product_lot){
this.display_lot_popup();
}
}else{
self.gui.show_popup('error',{
title :_t('Modification Resctricted'),
body :_t('Booked Order cannot be modified'),
});
}
},
});
});
but im getting an error
Uncaught TypeError: Cannot read property 'show_popup' of undefined
http://localhost:8071/web/content/554-cbfea6c/point_of_sale.assets.js:475
Traceback:
TypeError: Cannot read property 'show_popup' of undefined
at child.add_product (http://localhost:8071/web/content/554-cbfea6c/point_of_sale.assets.js:475:116)
at Class.click_product (http://localhost:8071/web/content/554-cbfea6c/point_of_sale.assets.js:326:257)
at Object.click_product_action (http://localhost:8071/web/content/554-cbfea6c/point_of_sale.assets.js:325:951)
at HTMLElement.click_product_handler (http://localhost:8071/web/content/554-cbfea6c/point_of_sale.assets.js:320:1738)
im sorry im really confuse do i still need to initialized the this.gui first?
even though i have var gui = require('point_of_sale.gui'); initialized already
when i log the this.gui to my console the output is undefined
You can access gui via posModel.
self.pos.gui.show_popup('error',{
title :_t('Modification Resctricted'),
body :_t('Booked Order cannot be modified'),
});
You can check an example at connect_to_proxy

add dependet values and and return all matched

I would like to add another dependency to look for in arrays. So if a user types the name of a student and the subject list,all the results of the supportlist are showed.
I have setup 3 arrays but i'm not sure how to go further.
gs code
function getStudentInfo(studentName){
//var lookupValue = "support";
var ss = SpreadsheetApp.openByUrl(url);
var ws =ss.getSheetByName("logboek1");
var lc =ss.getLastColumn();
//var data = ws.getRange(1, 1, ws.getLastRow(), 2).getValues()[0];
var data = ws.getRange(1, 1, ws.getLastRow(), lc).getValues();
//var index = data.indexOf(lookupValue) + 1;
var studentNameList = data.map(function(r) { return r[0]; });
var subjectList = data.map(function(r) { return r[1]; });
var supportList = data.map(function(r) { return r[4]; });
//Logger.log(supportList);
var position = studentNameList.indexOf(studentName);
if(position > -1){
return subjectList[position];
js code
}
function getEstimate(){
var zipCode = document.getElementById("zip").value;
if(zipCode){
google.script.run.withSuccessHandler(updateEstimate).getCost(zipCode);
}
}
function updateEstimate(cost){
document.getElementById("est").value =cost;
M.updateTextFields();
}
function getEstimate1(){
var studentName = document.getElementById("zip1").value;
if(studentName){
google.script.run.withSuccessHandler(updatestudentInfo)
.getStudentInfo(studentName);
}
}
function updatestudentInfo(info){
document.getElementById("est1").value =info;
M.updateTextFields();
Wat i would like is to add another dependency. So if a user types the studentName, (if the subjects are available for that student)chooses for the subjectList(that are available for that student) and then gets all of the results of the supportlist that belongs by the student.

Script work in a browser but not in NodeJS

I'm struggling trying to understand why this script works perfectly in the browser but not in Node.js in the server.
data = [{"stars": 3}, {"stars": 2}]
var ParseParameter = function(){
this.parser = "";
}
ParseParameter.prototype = {
setStrategy: function(parser) {
this.parser = parser;
},
parse: function(parameter) {
return this.parser.parse(parameter);
}
};
var IntegerParser = function(filter){
this.parameter = '';
this.filter = filter;
this.parse = function(parameter){
this.parameter = parseInt(parameter);
}
this.filterBy = function(item){
return item[this.filter] == this.parameter;
}
}
var filter = 'stars',
parameter = '2',
parseParameter = new ParseParameter();
var integerParser = new IntegerParser(filter);
parseParameter.setStrategy(integerParser);
parseParameter.parse(parameter);
var dataFiltered = data.filter(parseParameter.parser.filterBy);
console.log(dataFiltered);
At the server, I print in console the values of this.parameter and this.filter at the function filterBy and these are undefined
I'm running on Node.js version 8.11.2
Any advice will be appreciated.
The is may be due to problem of this keyword in your script. Inside an inner function this refers to window or global object. For example,
Inside the following code, this.filter of this.filterBy is not referring to the filter property that exists inside the scope of IntegerParser function instead it is referring the variable being defined as var filter = 'stars'. Change this name to something else and you'll see undefined and it won't work on browser as well. That's what could be your issue.
var IntegerParser = function(filter){
this.parameter = '';
this.filter = filter;
this.parse = function(parameter){
this.parameter = parseInt(parameter);
}
this.filterBy = function(item){
return item[this.filter] == this.parameter;
}
}
Instead of using this you could use a known solution for this problem by storing this to a variable for later usage. like in following example:
var IntegerParser = function(filter){
this.parameter = '';
this.filter = filter;
var self = this; // store this to self and use self in inner functions
this.parse = function(parameter){
self.parameter = parseInt(parameter);
}
this.filterBy = function(item){
return item[self.filter] == self.parameter;
}
}
Your entire code including my solution is as follow:
data = [{"stars": 3}, {"stars": 2}]
var ParseParameter = function(){
this.parser = "";
}
ParseParameter.prototype = {
setStrategy: function(parser) {
this.parser = parser;
},
parse: function(parameter) {
return this.parser.parse(parameter);
}
};
var IntegerParser = function(filter){
this.parameter = '';
this.filter = filter;
var self = this;
this.parse = function(parameter){
self.parameter = parseInt(parameter);
}
this.filterBy = function(item){
return item[self.filter] == self.parameter;
}
}
var filter = 'stars',
parameter = '2',
parseParameter = new ParseParameter();
var integerParser = new IntegerParser(filter);
parseParameter.setStrategy(integerParser);
parseParameter.parse(parameter);
var dataFiltered = data.filter(parseParameter.parser.filterBy);
console.log(dataFiltered);
It should work without any problem. Please try and see if it works for you.

How to return array from JavaScript function that retrieves data from text file?

I am building a Windows 8 Store app with HTML/CSS/JavaScript. I am reading in data from a text file through a function, and then putting that data into an array. I am trying to return the array through the function, but it is not working. Any help would be greatly appreciated. I've attached my code snippet.
// Load user data
var DefineUserData = function LoadUserData() {
return Windows.Storage.ApplicationData.current.localFolder.getFileAsync(loadfile).done(function (UserFile) {
return Windows.Storage.FileIO.readTextAsync(UserFile).done(function (fileResult) {
var userdata = new Object();
var dataobject = {};
var innercount;
var outercount;
var fileResultByLines = fileResult.split("\n");
for (outercount = 0; outercount <= (fileResultByLines.length - 2) ; outercount++) {
var tempArray = fileResultByLines[outercount].split(",");
dataobject.metrictitle = tempArray[0];
dataobject.numinputs = tempArray[1];
dataobject.inputs = new Array();
for (innercount = 0; innercount <= parseInt(dataobject.numinputs) ; innercount++) {
dataobject.inputs[innercount] = tempArray[innercount + 2];
}
userdata[outercount] = dataobject;
}
return userdata;
});
},
function (errorResult) {
document.getElementById("resbutton1").innerText = errorResult;
})
}
Your DefineUserData function is returning a Promise, not a value. Additionally done functions don't return anything. Instead you'll need to use then functions instead of done functions in DefineUserData and then handle add a done function (or then) to the code that calls this function.
Also, You can make your promises easier to read, and easier to work with by chaining then functions instead of nesting them.
Currently on Win7 at the office so I can't test this, but try something similar to this pseudo-code. Note then functions instead of done. The last then returns your data. Sample snippet afterwards to illustrate calling this and handling the result.
// modified version of yours
var DefineUserData = function LoadUserData() {
return Windows.Storage.ApplicationData.current.localFolder
.getFileAsync(loadfile)
.then(function (UserFile) {
return Windows.Storage.FileIO.readTextAsync(UserFile);
}).then(function (fileResult) {
var userdata = new Object();
var dataobject = {};
var innercount;
var outercount;
var fileResultByLines = fileResult.split("\n");
for (outercount = 0; outercount <= (fileResultByLines.length - 2) ; outercount++) {
var tempArray = fileResultByLines[outercount].split(",");
dataobject.metrictitle = tempArray[0];
dataobject.numinputs = tempArray[1];
dataobject.inputs = new Array();
for (innercount = 0; innercount <= parseInt(dataobject.numinputs) ; innercount++) {
dataobject.inputs[innercount] = tempArray[innercount + 2];
}
userdata[outercount] = dataobject;
}
return userdata;
},
function (errorResult) {
document.getElementById("resbutton1").innerText = errorResult;
});
}
// some other code...
DefineUserData.done(function (userdata) {
// do something
});

Categories

Resources