localStorageDB not persisting data between javascript files - javascript

I have 2 javascript files.
1 of those files functions looks like this.
var database = new localStorageDB("FormsDatabase", localStorage);
this.Create = function (item) {
database.insertOrUpdate("Value", { Id: item.Id }, item);
database.commit();
};
The other looks like this.
var database = new localStorageDB("FormsDatabase", localStorage);
this.SynchronizeValue = function () {
var items = database.queryAll("Value", { query: function (row) {
if (row.IsSent == false && row.IsDeleted == false)
{ return true; } else { return false; } }, limit: 100 });
};
Why is it that the first file i can do a query right after doing an insertOrUpdate and a commit and i can get a return but in the second file the "Value" tables contents have dissapeared?

Related

Keep LocalStorage after refreshing page

Currently, I enter data, it stores in the local storage and displays it accordingly. Here is the code for that flow:
Creating/Setting Data (in the create.js file)
let orders = [];
document.onreadystatechange = function () {
if (document.readyState === 'interactive') renderApp();
function renderApp() {
var onInit = app.initialized();
onInit.then(getClient).catch(handleErr);
function getClient(_client) {
window.client = _client;
//client.events.on('app.activated', onAppActivate1);
onAppActivate1();
}
}
};
function onAppActivate1() {
//intialize an array that will have all the keys user puts in
console.log('got here');
$("#btnCreateOrder").click(function () {
//orders = localStorage.getItem('orderlist');
let order = {
id: Date.now(),
order: document.getElementById('order').value,
name: document.getElementById('inputName').value,
date: document.getElementById('inputDate').value,
status: document.getElementById('inputStatus').value
}
orders.push(order);
if (!localStorage.getItem('orderlist') || JSON.parse(localStorage.getItem('orderlist')).length === 0) {
$window.localStorage.setItem('orderlist', JSON.stringify($scope.initData));
}
//localStorage.setItem('orderlist', JSON.stringify(orders));
client.instance.send({
message: {
orders: orders
}
});
client.instance.close();
});
}
function handleErr(err) {
console.log('Error Occuered', err);
}
Receiving/Displaying data (app.js)
function onAppActivate() {
//var displayID = new Array();
console.log("Hi!! We are in the app!");
client.instance.resize({ height: "350px" });
client.instance.receive(function (event) {
var data = event.helper.getData();
console.log("data is", data);
for (let i = 0; i < data.message.orders.length; ++i) {
console.log(data.message.orders.length);
const orderList = data.message.orders[i];
console.log("orderlist is ", orderList);
var order = document.createElement("div");
order.innerHTML = `<br/> Order#: ${orderList.order}<br/> Name: ${orderList.name}<br/>
Date: ${orderList.date} <br/> Status: ${orderList.status}`;
order.style.borderBottom = "1px solid black"
document.getElementById('orderhistory').appendChild(order);
}
})
when i refresh the app, my data stays but when i reload the browser, the data gets reset but I want the data to stay even if i reload the browser and keep appending to it

Getting Error on Two Events happening on same time

I'm having the activiti Bpmn file, in that there is having transition of task. While transition I need to create the due date for that new task. my problem is due date and new task happening on same time. because of that I'm getting error.
onClose: function (date) {
if (valid) {
date = Date.parse(date);
if (oldDate !== date) {
var tasks = getSet(context, 'task') || getSet(context, 'tasks'),
trans = Ember.get(context, 'transition') || Ember.get(context, 'propertyMap.transition'),
requestData = [];
if (!tasks.length) {
resolve();
return;
}
if (!trans) {
trans = 'Done';
}
tasks.forEach(function (task) {
requestData.push({ name: 'id', value: (Ember.get(task, 'id') || Ember.get(task, 'currentTask.id') )});
requestData.push({ name: 'transition', value: trans || '' });
});
if (context.get('serviceParams')) {
Object.asAjaxData(context.get('serviceParams')).forEach(function (param) {
requestData.push(param);
});
}
return (Core.services({
type: 'post',
service: 'workflow/task/transition',
data: requestData,
json: true
})
.done(function (res) {
Core.Action('Core:updateTask', context, { dtDue: date });
Core.model.ingestResources(res);
var inspected = Core.controller.detailsObject,
wf = res.workflows || {};
if (inspected) {
Object.keys(wf).forEach(function (w) {
var hist = wf[w].historicalTaskIds;
if (hist.contains(inspected.currentTaskId)) {
inspected.set('currentTaskId', wf[w].openTaskIds[0]);
}
});
}
resolve();
})
.fail(function (xhr, status, error) {
Core.Error.show(error);
})
.always(function () {
tasks.forEach(function (task) {
if (Ember.get(task, 'isClip')) {
Core.model.clip.clear();
}
});
var wfController = Core.Tab.Workflow.getController();
var sel = wfController.get('selection');
wfController.reloadResultSet();
var rs = wfController.get('resultSet');
rs && rs.done(function () {
var s = Ember.Set.create();
rs.get('content').forEach(function (item) {
if (!item) { return; }
s.addObject(item);
});
sel.forEach(function (item) {
if (!s.contains(item)) {
sel.remove(item);
}
});
});
sel.clear();
resolve(tasks);
})
);
}
}
}
In that Core.Action('Core:updateTask', context, { dtDue: date }); is using for updating the duedate. If I use on the top If statement Due Date is updated, but Transistion is not happening. If I'm using on the done function, the transistion is happened and moved to the new Task Id. Because of that it searching Task Id and showing error.
Please provide me suggestion on this. I need to create both the Transistion and meanwhile update the date.

Backbone model when created already has attributes

In my my application I do something like this to create a new model,
this.model = new App.Models.Organisation;
The code for the model looks like this,
'use strict'
App.Models.Organisation = Backbone.Model.extend({
urlRoot: "http://" + App.API_ROOT + "/organisations",
defaults: {
//members : new App.Collections.Users
},
initialize: function() {
//Gets
var members = this.get('users');
var projects = this.get('projects');
var teams = this.get('teams');
var clients = this.get('clients');
console.log(members);
console.log(projects);
console.log(teams);
console.log(clients);
//Sets
if(members != undefined) {
this.set('members', App App.Collections.Users(members));
} else {
this.set('members', App App.Collections.Users);
}
if(projects != undefined) {
this.set('projects', new App.Collections.Projects(projects));
} else {
this.set('projects', new App.Collections.Projects);
}
if(teams != undefined) {
this.set('teams', new App.Collections.Teams(teams));
} else {
this.set('teams', new App.Collections.Teams);
}
if(clients != undefined) {
this.set('clients', new App.Collections.Clients(clients));
} else {
this.set('clients', new App.Collections.Clients);
}
},
validate: function() {
}
});
However when log the new model where I expect to see empty attributes I get the following:
Why would teams and projects have a value when the model is newly created?
The teams collections looks like this,
'use strict'
App.Collections.Teams = Backbone.Collection.extend({
url: 'http://' + Pops.API_ROOT + '/teams',
model: Pops.Models.Team,
initialize: function() {
var members = this.get('members');
this.set('members', new App.Collections.Users(members));
},
search: function(filterValue) {
var matcher = new RegExp(filterValue);
var found_models = this.filter(function(model) {
return matcher.test(model.get('name'));
});
return found_models;
},
});
and the projects collection like this,
App.Collections.Projects = Backbone.Collection.extend({
url: 'http://' + App.API_ROOT + '/project',
model: App.Models.Project,
sort_key: "name",
sort_order: 1,
parent_filter: false,
filters: [1,2,3],
initialize:function() {
var pm = this.get('projectmanager');
this.set('project_manager', new App.Models.User(pm));
var sp = this.get('salesperson');
this.set('sales_person', new App.Models.User(sp));
this.sortByField('created_at', 'desc');
},
comparator: function (item1, item2) {
var val1 = item1.get(this.sort_key);
var val2 = item2.get(this.sort_key);
if (typeof (val1) === "string") {
val1 = val1.toLowerCase();
val2 = val2.toString().toLowerCase();
}
var sortValue = val1 > val2 ? 1 : -1;
return sortValue * this.sort_order;
},
sortByField: function(fieldName, orderType) {
this.sort_key = fieldName;
this.sort_order = orderType == "desc" ? -1 : 1;
console.log(this.sort_order);
this.sort();
},
sortStatus: function( filters ) {
this.filters = filters;
this.each(function(project){
project.set('visible', _.contains(filters, parseInt(project.get('status'))));
});
},
myProjects: function() {
this.each(function(project){
if(project.get('user_id') == '1' && project.get('organisation_id') == null) {
project.set('visible', true);
} else {
project.set('visible', false);
}
}, this);
},
status: function( status ) {
if(this.parent_filter == false) {
//Filter all projects on the dashboard
this.each(function(project){
project.get('visible', true);
project.set('visible', project.get('status') == String(status) );
});
} else {
//Filter only projects that are currently visible
this.each(function(project) {
if(project.get('visible')) {
project.set('visible', project.get('status') == String(status) );
}
});
}
},
otherProjects: function() {
this.each(function(project){
if(project.get('organisation_id') != null) {
project.set('visible', true);
} else {
project.set('visible', false);
}
}, this);
},
sortBy: function(filterBy, orderBy) {
this.sortByField(filterBy, orderBy);
this.sort();
},
search: function(filterValue) {
var matcher = new RegExp(filterValue);
var found_models = this.filter(function(model) {
return matcher.test(model.get('name'));
});
return found_models;
},
});
I see what's going on now, in your teams collection initialize method you have this line:
this.set('members', new App.Collections.Users(members));`
So this is calling set on a collection which is different from calling set on an individual model.
On a collection set treats the first element as an array of models. You are passing 'members' as the first parameter and this adding a model to the collection with every character in the string as one attribute of that model
On a model, set expects either an attributes hash to be passed or 2 parameters attribute name and value to be passed, and will set the model attributes accordingly.
Basically you cannot treat the collection as an individual model.
If you want to keep a reference to the members from the teams collection, why not keeping a reference like this.members = new App.Collections.Users(members) that you can access from other places in the teams collection?

Constructing fuelux datagrid datasource with custom backbone collection

I am trying to build datagrid with sorting, searching and paging enabled. Therefore, I am using fuelux-datagrid.
MY backbone view looks like this:
var app = app || {};
$(function ($) {
'use strict';
// The Players view
// ---------------
app.PlayersView = Backbone.View.extend({
template: _.template( $("#player-template").html() ),
initialize: function () {
if(this.collection){
this.collection.fetch();
}
this.listenTo(this.collection, 'all', this.render);
},
render: function () {
this.$el.html( this.template );
var dataSource = new StaticDataSource({
columns: [
{
property: 'playername',
label: 'Name',
sortable: true
},
{
property: 'age',
label: 'A',
sortable: true
}
],
data: this.collection.toJSON(),
delay: 250
});
$('#MyGrid').datagrid({
dataSource: dataSource,
stretchHeight: true
});
}
});
});
The player template just contain the template as given in fuelux datagrid . My routing code somewhere instantiate app.playerview with collection as
new app.PlayersView({
collection : new app.PlayersCollection
}));
My players collection contains list of player model as below
[{
"id":1,
"playername":"rahu",
"age":13
},
{
"id":2,
"playername":"sahul",
"age":18
},
{
"id":3,
"playername":"ahul",
"age":19
}]
My datasource class/function to construct datasoruce with columns and data method is as given in datasource constructor
However, I get the error the " datasource in not defined ". Can anybody help me?
I just wanted to hack the code so that instead of datasource constructed from local data.js in given example, I want to construct the datasource so that it takes data from playercollection.
Also, how to add the one extra column so that we can put edit tag insdie and its should be able to edit the particular row model on clicking that edit.
I have been stucking around these a lot. It would be great help to figure out the answer.
I was stucking around datasource.
I modified the datasource as follows and then it worked.
var StaticDataSource = function (options) {
this._formatter = options.formatter;
this._columns = options.columns;
this._delay = options.delay || 0;
this._data = options.data;
};
StaticDataSource.prototype = {
columns: function () {
return this._columns;
},
data: function (options, callback) {
var self = this;
setTimeout(function () {
var data = $.extend(true, [], self._data);
// SEARCHING
if (options.search) {
data = _.filter(data, function (item) {
var match = false;
_.each(item, function (prop) {
if (_.isString(prop) || _.isFinite(prop)) {
if (prop.toString().toLowerCase().indexOf(options.search.toLowerCase()) !== -1) match = true;
}
});
return match;
});
}
// FILTERING
if (options.filter) {
data = _.filter(data, function (item) {
switch(options.filter.value) {
case 'lt5m':
if(item.population < 5000000) return true;
break;
case 'gte5m':
if(item.population >= 5000000) return true;
break;
default:
return true;
break;
}
});
}
var count = data.length;
// SORTING
if (options.sortProperty) {
data = _.sortBy(data, options.sortProperty);
if (options.sortDirection === 'desc') data.reverse();
}
// PAGING
var startIndex = options.pageIndex * options.pageSize;
var endIndex = startIndex + options.pageSize;
var end = (endIndex > count) ? count : endIndex;
var pages = Math.ceil(count / options.pageSize);
var page = options.pageIndex + 1;
var start = startIndex + 1;
data = data.slice(startIndex, endIndex);
if (self._formatter) self._formatter(data);
callback({ data: data, start: start, end: end, count: count, pages: pages, page: page });
}, this._delay)
}
};
Infact, I just removed following code and its associated braces.
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(['underscore'], factory);
} else {
root.StaticDataSource = factory();
}
}(this, function () {
I dont know what exactly the above code is doing an what dependdencies they have over.

KnockOutJS trigger parent function on child subscribe

I am currently trying to learn KnockOutJS. I thought it would be a great idea to create a simple task-list application.
I do not want to write a long text here, let's dive into my problem. I appreciate all kind of help - I am new to KnockOutJS tho!
The tasks are declared as followed:
var Task = function (data) {
var self = this;
self.name = ko.observable(data.name);
self.status = ko.observable(data.status);
self.priority = ko.observable(data.priority);
}
And the view model looks like this
var TaskListViewModel = function() {
var self = this;
self.currentTask = ko.observable();
self.currentTask(new Task({ name: "", status: false, priority: new Priority({ name: "", value: 0 }) }));
self.tasksArr = ko.observableArray();
self.tasks = ko.computed(function () {
return self.tasksArr.slice().sort(self.sortTasks);
}, self);
self.sortTasks = function (l, r) {
if (l.status() != r.status()) {
if (l.status()) return 1;
else return -1;
}
return (l.priority().value > r.priority().value) ? 1 : -1;
};
self.priorities = [
new Priority({ name: "Low", value: 3 }),
new Priority({ name: "Medium", value: 2 }),
new Priority({ name: "High", value: 1 })
];
// Adds a task to the list
// also saves updated task list to localstorage
self.addTask = function () {
self.tasksArr.push(new Task({ name: self.currentTask().name(), status: false, priority: self.currentTask().priority() }));
self.localStorageSave();
self.currentTask().name("");
};
// Removes a task to a list
// also saves updated task list to localstorage
self.removeTask = function (task) {
self.tasksArr.remove(task);
self.localStorageSave();
};
// Simple test function to check if event is fired.
self.testFunction = function (task) {
console.log("Test function called");
};
// Saves all tasks to localStorage
self.localStorageSave = function () {
localStorage.setItem("romaTasks", ko.toJSON(self.tasksArr));
};
// loads saved data from localstorage and parses them correctly.
self.localStorageLoad = function () {
var parsed = JSON.parse(localStorage.getItem("romaTasks"));
if (parsed != null) {
var tTask = null;
for (var i = 0; i < parsed.length; i++) {
tTask = new Task({
name: parsed[i].name,
status: parsed[i].status,
priority: new Priority({
name: parsed[i].priority.name,
value: parsed[i].priority.value
})
});
self.tasksArr.push(tTask);
}
}
};
self.localStorageLoad();
}
What I want to do in my html is pretty simple.
All tasks I have added are saved to localStorage. The save function is, as you can see, called each time an element has been added & removed. But I also want to save as soon as the status of each task has been changed, but it is not possible to use subscribe here, such as
self.status.subscribe(function() {});
because I cannot access self.tasksArr from the Task class.
Any idea? Is it possible to make the self.tasksArr public somehow?
Thanks in advance!
Try this:
self.addTask = function () {
var myTask = new Task({ name: self.currentTask().name(), status: false, priority: self.currentTask().priority() })
myTask.status.subscribe(function (newValue) {
self.localStorageSave();
});
self.tasksArr.push(myTask);
self.localStorageSave();
self.currentTask().name("");
};

Categories

Resources