There is a list of news article in a page. Everytime user clicks on it, it saves news id and title to localstorage. My code is replacing localstorage data everytime I click new item.
How do I append new data into localStorage ?
Setting localStorage
awardForArticleRead: function(latestNews){
var articleData = {};
articleData['newsId'] = latestNews.news_id;
articleData['newsTitle'] = latestNews.title;
localStorage.setItem("articleRead", JSON.stringify(articleData));
},
calling function while it goes to detail page
newsDetail: function(key, id) {
var _this=this;
newsDetail = API_DATA['getLatestNews'][key];
myApp.mainView.loadPage('news1.html');
myApp.onPageInit("news_detail", function(page){
_this.awardForArticleRead(newsDetail);
_this.showNewsDetails(newsDetail);
})
},
You need to read the old data, convert to object (JSON.parse), add the new data, then write the amended data to localStorage
awardForArticleRead: function(latestNews){
var store = JSON.parse(localStorage.getItem("articleRead") || '[]');
store.push({
newsId: latestNews.news_id,
newsTitle: latestNews.title
});
localStorage.setItem("articleRead", JSON.stringify(store));
},
this would result in an array of items, like:
[{
newsId: 1,
newsTitle: 'title 1'
}, {
newsId: 2,
newsTitle: 'title 2'
}, {
newsId: 3,
newsTitle: 'title 3'
}]
so other code that reads the localStorage would have to be changed appropriately
Alternatively:
awardForArticleRead: function(latestNews){
var store = JSON.parse(localStorage.getItem("articleRead") || '{}');
store[latestNews.news_id] = latestNews.title;
localStorage.setItem("articleRead", JSON.stringify(store));
}
would result in the data being:
{
1: 'title1',
2: 'title2',
3: 'title3',
}
where 1,2,3 are the news_id's
As you have not shown how the localStorage data is used (read) then I can't really say which is the better option for you
There is no set add or append function, however you can simply gather the old data, combine them in the code and replace the new data into local storage.
Something like this:
function addToLocalStorage(nameOfItem, newData){
var oldData = localStorage.getItem(nameOfItem);
if(oldData !== null) {
localStorage.setItem(nameOfItem, oldData + newData);
} else {
localStorage.setItem(nameOfItem, newData);
}
}
Related
Im trying to separate out the functionality of my model and the data so ive created a separate json file with a basic table
when my model builds it creates an object and i need it to create a value in it based on a value coming in:
{
"1":"apple",
"2":"banana",
"3":"orange",
"4":"grape"
}
async save (xmlOrder) {
let customerOrder = {
ID: xmlOrder.ID,
Name: xmlOrder.Name ,
ItemCode: xmlOrder.ItemCode ,
Fruit: (This set by referencing the json, based on the Item code coming in above)enter code here
}
You can import that json object in file where you're having your model, than based on input to function you can get value out of object.
let obj = {"1":"apple","2":"banana","3":"orange","4":"grape"}
function save (xmlOrder) {
let customerOrder = {
ID: xmlOrder.ID,
Name: xmlOrder.Name ,
ItemCode: xmlOrder.ItemCode ,
Fruit: obj[xmlOrder.ItemCode] || 'Not in list',
}
return customerOrder
}
console.log(save({ID:33,Name:'Name',ItemCode:'2'}))
console.log(save({ID:303,Name:'Name1',ItemCode:'21'}))
I have one template, let's call it Template A that prints JSON data into a table, one column includes a button which is conditionally rendered when has_violations equals true.
An example of the table:
Table
What I want to accomplish is to take the driver_id that is associated with that particular row into the router link and have it passed onto a different template file let's call it Template B.
But how can I accomplish this using Vuex Store?
Sample JSON data:
{"driver_id":1,"driver_name":"{driver_first_name}, {driver_last_name}","driver_truck":"13","driver_trailer":"83","driver_status":"driving","has_violations":false},
{"driver_id":2,"driver_name":"{driver_first_name}, {driver_last_name}","driver_truck":"58","driver_trailer":"37","driver_status":"sleeping","has_violations":true},
{"driver_id":3,"driver_name":"{driver_first_name}, {driver_last_name}","driver_truck":"80","driver_trailer":"27","driver_status":"driving","has_violations":true},
Basic steps:
Get index of row on button click.
Get index of JSON data using value from Step 1.
Store the JSON data from Step 2 into Vuex.
Send user to Template B using router.
Retrieve data from Store when in Template B
Because you did not show your exact structure, the code below is just a basic structure.
Here's the code:
/* VUEX demo */
new Vuex.Store({
state: {
driver_data: undefined
},
mutations: {
recordDriver({ state }, payload){
state.driver_data = payload;
}
}
});
/* TEMPLATE A demo */
new Vue.component('template-a', {
data: function(){
return {
// Assume this is the JSON
driverJSON: [
{ driver_id: 1, driver_name: 'John Smith' },
{ driver_id: 2, driver_name: 'Bob John' }
]
};
},
methods: {
onButtonClicked: function(e){
const button = e.target;
const td = button.parentElement;
const tr = td.parentElement;
const indexOfTr = [...tr.parentElement.children].findIndex(row => row === tr);
const dataToStore = this.driverJSON[indexOfTr];
// Store data into $store
this.$store.commit('recordDriver', dataToStore);
// After storing, direct page using $router
this.$router.go({ ... });
}
}
});
/* TEMPLATE B demo */
new Vue.component('template-b', {
data: function(){
return {
// Get driver data using $store
driver: this.$store.state.driver_data
}
}
});
I like Yong's answer, but I would rather suggest you to pass the driverID as a prop to your route and then use a VueX getter to get the violations for the particular ID.
I use the function at the bottom to (re)create a store every time a grid within a (popup) window renders. However I don't understand why typeDetails is different from what gets logged on the longish line with Ext.pluck (based on https://stackoverflow.com/a/5709096/34806).
The former console log always prints what I expect, in the default case [{"label":"","value":""}], or when typeDetails is pre-populated something such as:
[{"label":"foo","value":"bar"},{"label":"what","value":"ever"}]
But the latter console.log always indicates an empty array, and I always get an empty grid. Could the line with pluck be at fault? That answer, though not the accepted or top-scoring, has been up-modded over 20. What else can I do to work through this.
listeners: {
render: {
fn: function (grid) {
var typeDetails = this.typeDetails || [{ 'label': '', 'value': ''}];
var store = Ext.create('Ext.data.Store', {
fields: ['label', 'value'],
data: [typeDetails]
});
console.log(Ext.encode(typeDetails));
console.log(Ext.encode(Ext.pluck(grid.store.data.items, 'data')));
grid.reconfigure(store);
}
}
}
UPDATE/OUTPUT
In response to Evan's comment "In the case where it defaults data, the store data will be [[{label: '', value: ''}]]" below is what is actually directly copied/pasted from my console:
[{"label":"","value":""}]
[]
However I think this is because the logging is before grid.reconfigure. Nevertheless shifting my console/logging as follows:
grid.reconfigure(store);
console.log(Ext.encode(this.typeDetails));
console.log(Ext.encode(typeDetails));
console.log(Ext.encode(Ext.pluck(grid.store.data.items, 'data')));
Results in the following mysterious output in the non-default case (when this.typeDetails is pre-populated):
[{"label":"foo","value":"bar"},{"label":"what","value":"ever"}]
[{"label":"foo","value":"bar"},{"label":"what","value":"ever"}]
[{"label":"","value":""}]
It's an editable grid, and the non-default values can only exist after the default empty row, so it's as though that empty row is being retained.
The following alternative approach works:
listeners: {
render: {
fn: function (grid) {
var store = Ext.create('Ext.data.Store', {
fields: ['label', 'value'],
data: []
});
if (this.typeDetails) {
for (var i = 0, n = this.typeDetails.length; i < n; i++) {
store.add(this.typeDetails[i]);
}
}
else {
store.add({ 'label': '', 'value': '' });
}
grid.reconfigure(store);
}
}
}
I am trying to put my ajax call returned data and other codes in one function.
This is for custom fckeditor plugin.
I have something like
function customTag(editor){
var id = editor.config.id;
var instance = this;
//my custom ajax wrapper…….
//the 'dbData' is holding the returned data from ajax.
ajax.onFinished = function(dbData){ console.log(dbData)};
//I want to return this object and use my ajax returned data
return {
title:'Link',
minWidth : 200,
minHeight : 200,
buttons : [CKEDITOR.dialog.okButton, CKEDITOR.dialog.cancelButton],
contents: [
{
id:'tab',
label: 'test here',
elements: [
{
type:'select',
id:'select box',
//I want to use the returned data below
items: [[dbData[0],0],[dbData[1],0] ]
}
]
}
]
}
}
CKEDITOR.dialog.add('customTag', function(editor){
return customTag(editor);
});
How would I be able to solve this. Thanks a lot!
Perform CKEDITOR.dialog.add() inside ajax.onFinished. In there, create the return object and use it directly for CKEditor. Either that, or use synchronous operations. Something like this:
ajax.onFinished = function(dbData){
var o = {
title:'Link',
minWidth : 200,
minHeight : 200,
buttons : [CKEDITOR.dialog.okButton, CKEDITOR.dialog.cancelButton],
contents: [
{
id:'tab',
label: 'test here',
elements: [
{
type:'select',
id:'select box',
items: [[dbData[0],0],[dbData[1],0] ] // Use dbData
}
]
}
]
};
CKEDITOR.dialog.add('customTag', function(editor){
return o;
});
};
If CKE has issues with calling dialog.add after it's been initialized, initialize it inside ajax.onFinished too.
I have store (and grid which displays its content), users could remove and add item but unfortunately one item after deleting could not be again added. I figure out problem is same id which was previously in store.
I use Dojo 1.6.
In firebug console I got:
Error: assertion failed in ItemFileWriteStore
Here is demo on jsFiddle: http://jsfiddle.net/MBBnE/
and here code:
dojo.require("dojo.data.ItemFileWriteStore");
dojo.addOnLoad(function() {
var d = {
items: [
{
id: 23,
x: 2},
],
identifier: "id",
};
var _store = new dojo.data.ItemFileWriteStore({
data: d,
});
var it = null;
_store.fetch({
query: {
id: "23*"
},
onItem: function(i) {
it = i;
}
})
_store.deleteItem(it);
console.info(it);
_store.newItem({id: 23, x: 3});
});
Hopefully I didn't misunderstand your question, but when you remove an item from a store if you want to re-add another item with the same id, you should save the store then re-add the item. Saving the store will clear all dirty items and allow the id to be reuse.
When you insert same value in Itemfilewritestore it will give you error 'assertion failed in ItemFileWriteStore'
To overcome this problem insert new or unique value in ItemFileWriteStore
_store.newItem({id: 24, x: 3});
I hope this will help you.
Finally I did a little workaround - create new store and copy all items to it:
oldStore.fetch({
onItem: function(it){
var newItem = {
id: it.id[0],
valueX: it.valueX[0],
(...)
};
newStore.newItem(newItem);
}
});