I do not know how can i delete element in localStorage loop
In save method i add element and check for it duplicate
explain please how can i delete element using for example only id or all values
My Factory
.factory('SaveDocuments', function() {
var documents = [];
save: function (id, name, link) {
if(documents.filter(function(a){return a.id==id}).length)
{ alert('conflict!'); }
else {
// add to it,
documents.push({id: id, name: name, link: link});
// then put it back.
localStorage.setItem('document', JSON.stringify(documents));
}
},
del: function(id, name, link) {
if(documents.filter(function(a){return a.id==id}).length) {
for (i = 0; i < localStorage.length; i++){
key = localStorage.key(i);
value = localStorage.getItem(key);
localStorage.removeItem(value);
console.log(value);
break;
}
}
else {
alert('conflict!');
}
}
}
MyController
.controller('PageSearchCtrl', function($scope, ConstSearch, SaveDocuments) {
$scope.saveDocument = function() {
//Create new project
$scope.document = [{"id": 1, "name": "new1", "link": "#/const"}];
SaveDocuments.save($scope.document[0].id,$scope.document[0].name,$scope.document[0].link);
};
$scope.deleteDocument = function () {
$scope.document = [{"id": 1, "name": "new1", "link": "#/const"}];
//Create new project
SaveDocuments.del($scope.document[0].id,$scope.document[0].name,$scope.document[0].link);
}
I recommend changing your service to something like the following:
.factory('SaveDocuments', function () {
var lsKey = 'document', // the key to store the docs in local storage under
documents = JSON.parse(localStorage.getItem(lsKey) || '[]'); // initialise from localStorage
function saveToLocalStorage() {
localStorage.setItem(lsKey, JSON.stringify(documents));
}
return {
save: function (id, name, link) {
if (documents.filter(function (a) {
return a.id == id;
}).length) {
alert('conflict!');
} else {
// add to it,
documents.push({
id: id,
name: name,
link: link
});
saveToLocalStorage();
}
},
del: function (id, name, link) {
// clear all if del() is called with no arguments or null for all args
if (!id && !name && !link) {
documents = [];
saveToLocalStorage();
return;
}
var initialLength = documents.length;
documents = documents.filter(function (doc) {
return (!id || doc.id !== id) && (!name || doc.name !== name) && (!link || doc.link !== link);
});
// if nothing was removed, show error
if (documents.length === initialLength) {
alert('conflict!');
} else {
saveToLocalStorage();
}
}
};
});
Note that I correctly initialised it from the local storage state when the application starts (so when you reload the page the data is there correctly), used a variable to hold the only key you use to store the data in local storage (to keep the code DRY), and fixed your del() method so it keeps ones which don't match the deletion criteria or deletes everything if no arguments passed in, then just overwrites the value in local storage with the updated state.
NB: You should test this, I did not do any testing to see if this works.
Related
I have a file with the following content:
function(doc) {
//pr reqs
var facet = true;
var store = true;
// Template start
var fields = {
}
// template end
noiseList = ["type", "objects", "value"]
const isNumeric = (num) => {
return !isNaN(num)
}
const emitIndex = () => {
if (doc.created_by_ref) {
Object.keys(fields).forEach(function(key) {
if (typeof fields[key] == 'object' && fields[key].length !== undefined) {
if (fields[key].length === 0) {
index(key, 'UNDEFINED', {
'store': store,
'facet': facet
});
} else {
fields[key].forEach(function(ele) {
index(key, ele.toString(), {
'store': store,
'facet': facet
});
})
}
} else {
index(key, fields[key].toString(), {
'store': store,
'facet': facet
});
}
})
}
}
Object.keys(doc).map(obj => {
if (typeof doc[obj] === 'object' && doc[obj] !== null) {
traverseObjectsInDoc(doc[obj], noiseCancelation(obj) ? "" : obj, doc.objects, false);
} else if (doc[obj] !== null && isValueType(obj) && !noiseCancelation(obj)) {
AddToFields(`${obj}`, doc[obj])
}
});
emitIndex();
}
As you I have two special sign there: template start and template end
what I am trying to achieve is to replace sth similar to
var fields = {
"test1": "test",
"test2": "test2"
}
instead of
var fields = {
}
in that file. And I should mention that this fields are generated in runtime so the content needs to be dynamic as well that is why I need this approach. All I can think of is to read the file
const searchAll1 = () => {
const contents = fs
.readFileSync("./lib/design_documents/searchAll", "utf8");
// find the template end and start replace the new fields some and return
};
and find the template end and start replace the new fields somehow and return. However I am not really sure if this is the best way?
What is the best way to do so?
Adjust the design of your function by adding a second parameter you can add the fields object dynamically whenever you call the function.
// your-script.js
module.exports = function(doc, fields) {
...
}
Then when you import and use the function, create a new object and pass it to your function and call it.
const yourFunction = require('./your-script.js');
let doc = someValue;
let fields = {
"test1": "test",
"test2": "test2"
}
yourFunction(doc, fields);
Im trying to compute if an array has a particular object that has a value which matches to what I want
The array is membersArray and here is where it comes from
<firebase-query
id="querymembers"
path="/members"
order-by-child="crew"
equal-to="[[routeData.key]]"
data="{{membersArray}}">
</firebase-query>
The property
_isUserAMember: {
type: Boolean,
computed: '_computeIfIsMember(membersArray,user)'
},
And the function itself
_computeIfIsMember: function(membersArray, user) {
if(user && membersArray) {
// var found = false;
// for(var i = 0; i < membersArray.length; i++) {
// if (membersArray[i].userid === user.uid) {
// found = true;
// break;
// }
// }
// return console.log(found);
return console.log(membersArray.some(function(el) {
return el.crew === username;
}));
}
},
I keep getting false. What could I be doing wrong ?
This is how the members path looks like
console.log(typeof(this.membersArray)); // object
Assuming that firebase query will only return a result if the user.uid equal-to the child, I don't think you need to recheck the result.
I have created a custom object that I am using in my extension. When I save objects of the type Group (my object type) and then later pull those objects out of storage, it appears that the prototype methods are no longer present. Now I read in the documentation that objects serialize down to object literals {} and I can't seem to figure out how to keep the methods with the objects. I have provided the code of the group class below. When I try and use one of the methods from the file below on an object that was retrieved from storage, I get an error that the function does not exist. I used a for in loop to loop through all of the properties and the object has the name and urls property. Any help would be greatly appreciated!
Group.js:
// Create the Group class
var Group = function (name, urls) {
this.name = name;
this.urls = urls;
};
// Clears all urls from the group
Group.prototype.clearUrls = function () {
this.urls = [];
};
// Adds the specified url to the group
Group.prototype.addUrl = function (url) {
this.urls.append(url);
};
// Removes the specified url from the group
Group.prototype.removeUrl = function (url) {
this.urls = this.urls.filter(function(_url){
return url !== _url;
});
};
// Renames the group
Group.prototype.rename = function (name) {
this.name = name;
};
// Checks whether or not the group contains the specified url
// Returns either true or false
Group.prototype.containsUrl = function (url) {
var contains = false;
for (var i = 0; i < this.urls.length; i++) {
if (this.urls[i] === url) {
contains = true;
break;
}
}
return contains;
};
EDIT:
Here is the background.js script, it shows how the object is retrieved and then how it is called later in the script. It fails when it receives the addUrl message and attempts to call containsUrl() on currentGroup.
// Global Variables
var currentGroup;
var groups = [];
var options = [];
// Short hand function to save the current data to storage
var saveData = function () {
// Save default options, currrentGroup, and groups
chrome.storage.sync.set({'options': options, 'currentGroup': currentGroup, 'groups': groups}, function() {
if (chrome.runtime.lastError) {
console.error("Could not save because: " + chrome.runtime.lastError);
}
});
}
// On start query for saved data to make sure data is current
chrome.storage.sync.get(function(items) {
// Check if there are groups
if (items['groups']) { // Set the groups
groups = items['groups'];
} else { // Create default group and add to list of groups
currentGroup = new Group('default', []);
groups = [currentGroup];
}
// Check for current group, if none set to first available group
if (items['currentGroup']) {
currentGroup = items['currentGroup'];
console.log(Object.getOwnPropertyNames(currentGroup));
} else {
currentGroup = groups[0];
}
// Check for the options
if (items['options']) {
options = items['options'];
} else {
// No options, set the default options and save them
options['overrideHomepages'] = true;
}
saveData();
// After data has been fetched bring up the tabs
chrome.tabs.query({'currentWindow': true}, function(tabs) {
for (var i = 0; i < currentGroup.urls.length; i++) {
if (options['overrideHomepages']) {
if (tabs[i].url.length > 0) {
chrome.tabs.update(tabs[0].id, {'url': currentGroup.urls[i]});
} else {
chrome.tabs.create({'url': currentGroup.urls[i]});
}
} else { // Don't override homepages or open tabs
chrome.tabs.create({'url': currentGroup.urls[i]});
}
currentGroup.urls[i]
}
}); // End tabs.query
}); // End storage.sync.get
// Add message listener
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
// If add url was sent
if (request.message === 'addUrl') {
console.log('Recieved message: ' + request.message);
// Check if the group contains the url already
if (currentGroup.containsUrl(sender.url) === false) {
currentGroup.addUrl(sender.url);
saveData();
sendResponse({'message': 'Saved ' + sender.url});
}
}
// If remove url was sent
if (request.message === 'removeUrl') {
// Check if the group contains the url
if (currentGroup.containsUrl(sender.url)) {
currentGroup.removeUrl(sender.url);
saveData();
sendResponse({'message': 'Removed ' + sender.url})
}
}
});
I believe currently chrome.storage is only used to save key-value items, not including prototype/functions. However, I didn't find any official docs about this.
One workaround would be using Group.prototype.containsUrl.call(currentGroup, sender.url), it allows you to invoke containsUrl with specifying the context for "this".
I am using JavaScript function in single page and I am calling the same function twice without refreshing page and I am also passing params value in function but when I am calling it second time then I am also finding previous time value of params I use at first time call.
For example: I am calling this function and sending '.assign_agents_popup_index' at second time and at first time I am passing '.add_agents_popup_index'.
showUnAssignAgentList('',response, '.assign_agents_popup_index');
my question is when i am going into this function and fetching third param second time then i am getting value of previous time as well.
showUnAssignAgentList(cookieLogin, _data, _parent)
Example
first time i call this function like :
showUnAssignAgentList('',response, '.add_agents_popup_index');
and when fetching param in function then _parent value i am getting '.add_agents_popup_index'
but when i call it second time
showUnAssignAgentList('',response, '.assign_agents_popup_index');
then I am getting value of _parent like '.add_agents_popup_index .assign_agents_popup_index' can you tel me how can i reset function value everytime i am calling it
function showUnAssignAgentList(cookieLogin, data, _parent) {
var user_data = {},
sorted_users = [],
list_names = [];
/* First we're going through the list of users to get the last names */
$.each(data.field_data.users, function(k, v) {
if(v.last_name && list_names.indexOf(v.last_name.toLowerCase()) < 0) {
list_names.push(v.last_name.toLowerCase());
}
});
/* Then we sort the array */
list_names.sort();
/* We build the function which will be use the second time we'll loop over users */
var build_sort_users = function(k, user) {
if(user.last_name) {
if(sorted_users[list_names.indexOf(user.last_name.toLowerCase())]) {
sorted_users[list_names.indexOf(user.last_name.toLowerCase())].push({
first_name: user.first_name,
last_name: user.last_name,
id: user.id
});
}
else {
sorted_users[list_names.indexOf(user.last_name.toLowerCase())] = [{
first_name: user.first_name,
last_name: user.last_name,
id: user.id
}];
}
}
};
if(data.data.id && 'agents' in data.data && data.data.agents.length > 0) {
$.each(data.field_data.users, function(k, v) {
if(data.data.agents.indexOf(v.id) >= 0) {
user_data[v.id] = {
first_name: v.first_name,
last_name: v.last_name,
id: v.id
}
}
build_sort_users(k, v);
});
}
else {
$.each(data.field_data.users, function(k, v) {
build_sort_users(k, v);
});
}
$('#select_all_agents').click(function() {
$('.select_agent').prop('checked', $(this).is(':checked'));
});
var available_user = loadViewTemplate('available_user'),
selected_agent = loadViewTemplate('selected_agent'),
count_agents = 0,
count_un_agents = 0;
$('.assign_agents_popup').delegate('.queue_agent', 'click', function() {
var data = $(this).data();
$.tmpl(available_user, data).prependTo('#queue-view-unassigned-agent');
console.log(_parent);
$(this).parent().remove();
$('.count_un_agents').html(++count_un_agents);
$('.count_agents').html(--count_agents);
});
$('.assign_agents_popup').delegate('.user_box', 'click', function() {
var data = $(this).data();
$.tmpl(selected_agent, data).prependTo('#queue-view-assigned-agent');
console.log(_parent);
$(this).parent().remove();
$('.count_agents').html(++count_agents);
$('.count_un_agents').html(--count_un_agents);
});
$.each(sorted_users, function(k, v) {
$.each(v, function(k2, v2) {
if(!(v2.id in user_data)) {
count_un_agents++;
mergeTemplate(available_user, '#queue-view-unassigned-agent', v2);
}
else {
count_agents++;
mergeTemplate(selected_agent, '#queue-view-assigned-agent', v2);
}
});
});
$('.count_un_agents').html(count_un_agents);
$('.count_agents').html(count_agents);
}
In localStorage I have a object records. It has many fields
records[recordId] and I want to be able to delete these entries. Below is my delete function but it does not work. All the records remain attached to the records object in local storage. Not sure what is wrong as I am deleting in what looks like the correct manner. When I print the records object all the records are still there along with their keys????
function deleteLocalRecord(recordId) {
var records = localStorage.getItem('records');
var theRecords;
if (supports_html5_storage()) {
if (records == null) {
theRecords = {};
} else {
// parse the records
theRecords = JSON.parse(records);
}
theRecords[recordId] = ''; // set the record to empty string.
delete theRecords[recordId]; // delete the record
// reset the records object in local storage after change
localStorage.setItem('records', JSON.stringify(theRecords));
}
}
function supports_html5_storage()
{
try
{
return 'localStorage' in window && window['localStorage'] !== null;
}
catch (e)
{
return false;
}
}
Live demo
function deleteLocalRecord(recordId) {
if (localStorageEnabled()) {
var records = localStorage.getItem('records'),
theRecords = JSON.parse(records) || {};
print(JSON.stringify(theRecords)); // before
delete theRecords[recordId]; // delete
print(JSON.stringify(theRecords)); // after
localStorage.setItem('records', JSON.stringify(theRecords));
print(localStorage.getItem("records"));
}
}
var records = {
"test": "test",
"stuff": "stuff"
};
localStorage.setItem("records", JSON.stringify(records));
deleteLocalRecord("test");
function print(x) {
document.body.innerHTML += "<p>" + x + "</p>";
};
function localStorageEnabled() {
return typeof window["localStorage"] !== "undefined";
};