AS3 SQLite DELETE statement don't give result - database

When I delete row from DB, it deletes row, but I don't get event, that it deleted row (I need to refresh list after user delete something). Here are methods for handle results from DB:
private final function onReady(e:EventWithMessage):void
{
switch (action)
{
case "get files":
dispatchEvent(new EventWithMessage(EventWithMessage.FILES, {files: null}));
break;
case "save note":
dispatchEvent(new EventWithMessage(EventWithMessage.SAVED, { ID:e.message.ID } ));
break;
case "delete note":
// Saving and getting files above work! And this is not working
dispatchEvent(new EventWithMessage(EventWithMessage.DELETED, { } ));
break;
}
action = null;
}
private final function onData(e:EventWithMessage):void
{
DATA = e.message.data;
switch (action)
{
case "get files":
// some code was here
dispatchEvent(new EventWithMessage(EventWithMessage.FILES, {files: fileArray}));
break;
case "load note":
dispatchEvent(new EventWithMessage(EventWithMessage.FILE, { text:DATA[0].text } ));
break;
case "delete note":
// And even here it isn't working
dispatchEvent(new EventWithMessage(EventWithMessage.DELETED, { } ));
break;
}
action = null;
}
Method for DELETE:
public final function deleteNote(ID:int):void
{
SQLiteManager.SQLM.Operations(String("DELETE FROM Notes WHERE id = " + ID));
action = "delete note";
}
And methods in SQLiteManager (my class):
public final function Operations(command:String, parameters:Array = null)
{
statement = new SQLStatement ();
statement.sqlConnection = connection;
statement.text = command;
if (parameters && parameters.length > 0)
{
for (i = 0; i < parameters.length; i++)
{
statement.parameters[i] = parameters[i];
}
}
statement.execute (-1,responder);
}
Responder has two methods :
private final function handleSuccess (result:SQLResult):void
{
if (result.data)
{
dispatchEvent(new EventWithMessage(EventWithMessage.SQLDATA, { data:result.data} ));
}
else
{
dispatchEvent(new EventWithMessage(EventWithMessage.READY, { ID:result.lastInsertRowID } ));
}
}
private final function handleError (e:SQLError):void
{
dispatchEvent (new EventWithMessage(EventWithMessage.ERROR,{error:e.message}));
}
Is there any mistake or it just don't give any result after DELETE? Help please.
EDIT: While I wait for answer - I use timer (1 second after DELETE it refresh file list). Maybe it's an good alternative to event?
EDIT 2 action variable is null, when it comes to dispatch event O_o Why it is null? Oh my god.

RESOLVED!!! There was an event, I made some "trace" and found out that problem was in action variable, it was null, when event had been dispatched. I deleted lines action = null; and now everything works well. Hooray :)

Related

Use for of loop to iterate the array

Assignment task4: Add the listStudents() method
In this task, you will add a method to the Bootcamp class that lists all the registered students' names and emails.
Create a method in the Bootcamp class named listStudents().
In the method body:
Check if the this.students array is empty.
If so, console.log() the message:
No students are registered to the ${this.name} bootcamp.
Then return the boolean value of false.
Otherwise, console.log() the line:
The students registered in ${this.name} are:
Then iterate through the entire this.students array and console.log() the name and email of each student on one line for each student. See the Testing section below for an example of the expected output.
You can do this with the for...of loop.
Finally, return the boolean value of true.
Testing code:
const runTest = (bootcamp, student) => {
const attemptOne = bootcamp.registerStudent(student);
const attemptTwo = bootcamp.registerStudent(student);
const attemptThree = bootcamp.registerStudent(new Student("Babs Bunny"));
if ( attemptOne && !attemptTwo && !attemptThree) {
console.log("TASK 3: PASS");
}
bootcamp.registerStudent(new Student('Babs Bunny', 'babs#bunny.com'));
if (bootcamp.listStudents()) {
console.log("TASK 4: PASS 1/2");
}
bootcamp.students = [];
if (!bootcamp.listStudents()) {
console.log("TASK 4: PASS 2/2");
}
};
My code below does not work. Please help me review. Thanks
class Bootcamp {
constructor(name, level, students = []){
this.name = name;
this.level = level;
this.students = students;
}
registerStudent(studentToRegister){
if (!studentToRegister.name || !studentToRegister.email) {
console.log("Invalid name or email");
return false;
} else if(this.students.filter(s => s.email === studentToRegister.email).length) {
console.log("This email is already registered");
return false;
} else {
this.students.push(studentToRegister)
console.log(`Successful registration ${studentToRegister.name} ${Bootcamp.name}`)
return true;
}
}
listStudent(registerStudent){
if(this.students.length === 0)
{
console.log(`No students are registered to the ${this.name} bootcamp.`);
return false;
}
else
{
console.log(`The students registered in ${this.name} are:`);
for(const registerStudent of this.students)
{
console.log("Name:" + registerStudent[name] + "Email:" + registerStudent[email]);
return true;
}
}
}
}
listStudents() {
if (this.students.length == 0) {
console.log("No students are registered to the ${this.name} bootcamp");
return false;
} else {
console.log("The students registered in ${this.name} are:");
for (let student of this.students) {
console.log(`Name: ${student.name} Email: ${student.email}`);
}
return true;
}
}
}

How to unset a laravel session array

Hi I'm trying to remove a product array inside my cart session when the quantity is 1 and user tries to remove it, simply unsets that.
Here is my code:
public function remove($id)
{
if (session('cart')) {
foreach (session('cart') as $product) {
if ($product['id'] == $id) {
if ($product['qty'] == 1) {
} else {
$product['qty'] = $product['qty'] - 1;
}
};
}
Session::put('cart', session('cart'));
return redirect()->back();
}
}
I tried to use Session::forget('cart.'$num) but having some more issues.
Take your session edit it, and then re-set it:
$cart = session('cart');
array_forget($cart, $num);
session()->put('cart', $cart);

How to instantiate an array in TypeScript which should contain strings?

I am new to TypeScript and working on a server monitoring webApp. I have a method which should save the status of pings and endpoints into an array. Then it should determine the status of the servers depending on the entries in that array. The method should be working correctly I assume, but I think I am not initialising the array in a proper way.
setServersStatus() {
let allStatus: String[] = new Array(); // Here I get a Warning "Instantiation can be simplified"
for (let server of this.servers) {
if (server.restendpoints != null) {
for (let rest of server.restendpoints) {
switch (rest.status) {
case "OK":
allStatus.push("OK");
break;
case "WARNING":
allStatus.push("WARNING");
break;
case "ERROR":
allStatus.push("ERROR");
break;
default:
console.log('status empty');
}
}
}
if (server.ping != null) {
switch (server.ping.status) {
case "OK":
allStatus.push("OK");
break;
case "WARNING":
allStatus.push("WARNING");
break;
case "ERROR":
allStatus.push("ERROR");
break;
default:
console.log('status empty');
}
}
if (allStatus.indexOf('ERROR')) {
server.status = 'ERROR';
}
else if (allStatus.indexOf('WARNING')) {
server.status = 'WARNING';
}
else if (allStatus.indexOf('OK')) {
server.status = 'OK';
}
allStatus.length = 0;
}
}
I also tried to initialize in the following way, but it didn't work:
let allStatus = []; // Here it says "Variable allStatus implicitly has an any[] type"
So how do I initialize an array properly in TypeScript?
You can declare a typed array like this
let allStatus: string[] = [];
or like this
let allStatus: Array<string> = [];

How to save Mobx state in sessionStorage

Trying to essentially accomplish this https://github.com/elgerlambert/redux-localstorage which is for Redux but do it for Mobx. And preferably would like to use sessionStorage. Is there an easy way to accomplish this with minimal boilerplate?
The easiest way to approach this would be to have a mobx "autorun" triggered whenever any observable property changes. To do that, you could follow my answer to this question.
I'll put some sample code here that should help you get started:
function autoSave(store, save) {
let firstRun = true;
mobx.autorun(() => {
// This code will run every time any observable property
// on the store is updated.
const json = JSON.stringify(mobx.toJS(store));
if (!firstRun) {
save(json);
}
firstRun = false;
});
}
class MyStore {
#mobx.observable prop1 = 999;
#mobx.observable prop2 = [100, 200];
constructor() {
this.load();
autoSave(this, this.save.bind(this));
}
load() {
if (/* there is data in sessionStorage */) {
const data = /* somehow get the data from sessionStorage or anywhere else */;
mobx.extendObservable(this, data);
}
}
save(json) {
// Now you can do whatever you want with `json`.
// e.g. save it to session storage.
alert(json);
}
}
Turns out you can do this in just a few lines of code:
const store = observable({
players: [
"Player 1",
"Player 2",
],
// ...
})
reaction(() => JSON.stringify(store), json => {
localStorage.setItem('store',json);
}, {
delay: 500,
});
let json = localStorage.getItem('store');
if(json) {
Object.assign(store, JSON.parse(json));
}
Boom. No state lost when I refresh the page. Saves every 500ms if there was a change.
Posting the example from here: https://mobx.js.org/best/store.html
This shows a cleaner method of detecting value changes, though not necessarily local storage.
import {observable, autorun} from 'mobx';
import uuid from 'node-uuid';
export class TodoStore {
authorStore;
transportLayer;
#observable todos = [];
#observable isLoading = true;
constructor(transportLayer, authorStore) {
this.authorStore = authorStore; // Store that can resolve authors for us
this.transportLayer = transportLayer; // Thing that can make server requests for us
this.transportLayer.onReceiveTodoUpdate(updatedTodo => this.updateTodoFromServer(updatedTodo));
this.loadTodos();
}
/**
* Fetches all todo's from the server
*/
loadTodos() {
this.isLoading = true;
this.transportLayer.fetchTodos().then(fetchedTodos => {
fetchedTodos.forEach(json => this.updateTodoFromServer(json));
this.isLoading = false;
});
}
/**
* Update a todo with information from the server. Guarantees a todo
* only exists once. Might either construct a new todo, update an existing one,
* or remove an todo if it has been deleted on the server.
*/
updateTodoFromServer(json) {
var todo = this.todos.find(todo => todo.id === json.id);
if (!todo) {
todo = new Todo(this, json.id);
this.todos.push(todo);
}
if (json.isDeleted) {
this.removeTodo(todo);
} else {
todo.updateFromJson(json);
}
}
/**
* Creates a fresh todo on the client and server
*/
createTodo() {
var todo = new Todo(this);
this.todos.push(todo);
return todo;
}
/**
* A todo was somehow deleted, clean it from the client memory
*/
removeTodo(todo) {
this.todos.splice(this.todos.indexOf(todo), 1);
todo.dispose();
}
}
export class Todo {
/**
* unique id of this todo, immutable.
*/
id = null;
#observable completed = false;
#observable task = "";
/**
* reference to an Author object (from the authorStore)
*/
#observable author = null;
store = null;
/**
* Indicates whether changes in this object
* should be submitted to the server
*/
autoSave = true;
/**
* Disposer for the side effect that automatically
* stores this Todo, see #dispose.
*/
saveHandler = null;
constructor(store, id=uuid.v4()) {
this.store = store;
this.id = id;
this.saveHandler = reaction(
// observe everything that is used in the JSON:
() => this.asJson,
// if autoSave is on, send json to server
(json) => {
if (this.autoSave) {
this.store.transportLayer.saveTodo(json);
}
}
);
}
/**
* Remove this todo from the client and server
*/
delete() {
this.store.transportLayer.deleteTodo(this.id);
this.store.removeTodo(this);
}
#computed get asJson() {
return {
id: this.id,
completed: this.completed,
task: this.task,
authorId: this.author ? this.author.id : null
};
}
/**
* Update this todo with information from the server
*/
updateFromJson(json) {
// make sure our changes aren't send back to the server
this.autoSave = false;
this.completed = json.completed;
this.task = json.task;
this.author = this.store.authorStore.resolveAuthor(json.authorId);
this.autoSave = true;
}
dispose() {
// clean up the observer
this.saveHandler();
}
}
Here, you can use my code, although it only supports localStorage you should be able to modify it quite easily.
https://github.com/nightwolfz/mobx-storage

angular-translate inside loop

I'm trying to construct a translated message by looping over an array of objects and then adding a new "message" property to that object containing the translated string. I see the correct message output while inside $translate.then(); but when I assign the message to the object it is undefined. What is the correct way to resolve the promise returned from $translate.then() and assign it to the "message" property?
//items.controller.js
function getItems() {
return itemsFactory.getItems()
.then(function (response) {
vm.items = initItemsList(response.activities);
});
}
function initItemsList(itemsList) {
for (var i = 0; i < itemsList.length; i++){
var activityType = itemsList[i].activityType;
switch (activityType){
case "HISTORY": {
var itemName = itemsList[i].item.itemName;
var itemVersion = itemsList[i].item.itemVersion;
$translate('activity.'+activityType, { itemname: itemName, itemversion: itemVersion }).then(function(content){
vm.itemContent = content;
console.log(vm.itemContent); // correct message displayed.
});
break;
}
default: {
break;
}
}
itemsList[i].message = vm.itemContent; // undefined
}
return itemsList;
}
// translation.json
"activity : {
"HISTORY" : "History for {{ itemname }} {{ itemversion }}."
}
Promises are always resolved asynchronously. So the statement
itemsList[i].message = vm.itemContent;
, which is executed right after the switch, is executed before the callback passed to the $translate promise. Just move the statement to the callback:
$translate('activity.'+activityType, { itemname: itemName, itemversion: itemVersion }).then(function(content){
vm.itemContent = content;
console.log(vm.itemContent);
itemsList[i].message = vm.itemContent;
});
As #Vegar correctly states, the code inside then is executed after the assignment so moving the assignment inside then function will take care of the problem. However, your itemsList will be returned from the function before all the translations are done so you will need to return a promise that resolves when all translations are done:
function initItemsList(itemsList) {
var allTranslations = [];
for (var i = 0; i < itemsList.length; i++){
var activityType = itemsList[i].activityType;
switch (activityType){
case "HISTORY": {
var itemName = itemsList[i].item.itemName;
var itemVersion = itemsList[i].item.itemVersion;
allTranslations.push($translate('activity.'+activityType, { itemname: itemName, itemversion: itemVersion }).then(function(content){
vm.itemContent = content;
itemsList[i].message = vm.itemContent;
}));
break;
}
default: {
break;
}
}
}
return $q.all(allTranslations);
}
The caller of your function will have to do like:
initItemList(itemList).then(function(translatedList){
//Do stuff with translated list
});

Resources