Javascript variable overriden issue in Expo createCategoryAsync - javascript

I know everyone may had this issue before and I think this one maybe the same but what I expected is the 'uniq_identifier' should be series numbers, like 0, 1, 2, 3.... but I always get 1 for ever.
enter code here
array.forEach(element => {
let categoryId = 'categoryId'
let body = 'Press and hold for more options, God bless USA!';
console.log(`completeID-${element}`);
var uniq_identifier = `completeID-${element}`;
Notifications.createCategoryAsync(uniq_identifier, [
{
actionId: uniq_identifier,
buttonTitle: `USA ${element}`,
isDestructive: false,
isAuthenticationRequired: false,
},
{
actionId: 'God and me',
buttonTitle: 'Delay',
isDestructive: false,
isAuthenticationRequired: false,
},
]).then(() => {
console.log('var in async: ', element);
});
});

Related

dynamicly nested object from another object

trying to figure out how to dynamicly create a new nested object from this one:
object1 = {
DataStore : false,
Header: false,
Footer : false,
Sidebar : false,
Main : false,
}
to nested one like this:
const registerComponentsLocal = {
'DataStore': {
'debug': false
},
'Header': {
'debug': false
},
'Footer': {
'debug': false
},
'Sidebar': {
'debug': false
},
'Main': {
'debug': false
},
}
keys and values have to by dynamic. Only important thing is a structure of the final object.
Any ideas would be greatly appricieated.
To create a new instance (i.e preserve the old one)
let originalObject = {
DataStore : false,
Header: false,
Footer : false,
Sidebar : false,
Main : false,
}
let newObject = Object.assign({}, originalObject) // Copies the original object
Object.entries(newObject).forEach(([key, value]) => newObject[key] = {debug: value})
Here's a method using reduce
Object.entries(object1)
.reduce((b,a) => ({...b, [a[0]] : {debug:a[1]}}), {})
To iterate, we need an array and Object.entries gives us that. Then, using reduce, we iterate through each item in object1, and build a result. Here, this line ({...b, [a[0]] : {debug:a[1]}}) takes our accumulating object b and adds in the next iterable: {key: { debug: value}}`
let object1 = {
DataStore : false,
Header: false,
Footer : false,
Sidebar : false,
Main : false,
}
const registerComponentsLocal = Object.entries(object1).reduce((b,a) => ( {...b, [a[0]] : { debug:a[1]} }),{})
console.log(registerComponentsLocal)

Changing the value of a parameter based on spread operator

So let's say that I have an object literal, which is the following:
let test = {
settings: {
title: '',
has_content: true,
can_edit: false,
}
}
Now I have another object literal as shown below:
let test2 = {
...test,
settings: {
can_edit: true,
}
}
How can I bring over all the parameters from the test object literal but have the ability to change values in test2?
So ultimately, I'd like for this:
let test2 = {
settings: {
title: '', (This is default)
can_edit: true, (This value is changed)
has_content: true, (This is default)
}
}
Now, when I console.log test2, all that I see in the settings is the can_edit: true, but not the title or has_content.
You need to spread the test.settings in test2.settings to merge the properties and override with the latest one that are defined in test2.settings.
let test = {
settings: {
title: "",
has_content: true,
can_edit: false,
},
};
let test2 = {
settings: {
...test.settings,
can_edit: true,
},
};
console.log(test2);
Because you test.settings key will be replaced by test2.settings. so you should spread the test.setting into test2.settings like below
let test = {
settings: {
title: '',
has_content: true,
can_edit: false,
}
}
let test2 = {
settings: {
...test.settings,
can_edit: true,
}
}
console.log(test2)
It should be like this
let test2 = {
...test,
settings: {
...test.settings,
can_edit: true,
}
}
Explanation: You need to spread object by object. Be aware, if you use the spread before changing the values (like I did) your changes survive.

How to load the DataTable jQuery plugin when a Bootstrap modal window is completely loaded without getting asynchronous issues?

I am currently using Bootstrap v4.4.1 and the nodejs bootstrap versions of the plugin:
require('datatables.net-bs4')(window, $);
require('datatables.net-colreorder-bs4')(window, $);
require('datatables.net-fixedheader-bs4')(window, $);
First I load all the rows in the table that is inside the html of the Bootstrap modal window. All these operations are synchronous, so I don't see any issue here. Each one of the functions get_* just add node elements with jQuery.
for (var i = 0; i < cols.length; i++) {
var col_name = cols[i];
var name = self.get_col_name(col_name);
var data_type = self.get_data_type(col_name)
var attrs = self.pj_cols[col_name]['attrs'].join(', '); // TODO: translate to icons or extract just some of them?
var cb_export = self.get_cb_export(i, col_name);
var sel_cur_prec = self.get_cur_prec(col_name);
var txt_cur_unit = self.get_txt_cur_unit(col_name);
var set_bt = self.get_set_bt(col_name, i);
var tr = $('<tr>');
tr.append(
$('<td>', {html: cb_export }),
name,
$('<td>', {html: data_type }),
$('<td>', {text: attrs }),
$('<td>', {html: sel_cur_prec }),
$('<td>', {html: txt_cur_unit }),
$('<td>', {html: set_bt })
);
$('#table_column_project tbody').append(tr);
}
Then I load the modal window programmatically by clicking the button to trigger and show it
$('#modal_column_project').click();
And finally I run the DataTable() function in order to convert the table in a DataTable
$('#column_project_win').on('shown.bs.modal', function (e) {
$('#table_column_project').DataTable( {
scrollY: 400,
scrollCollapse: true,
paging: false,
searching: true,
ordering: true,
order: [[ 1, 'asc' ]],
info: false,
columnDefs: [
{ targets: '_all', visible: true, },
{ targets: [6], orderable: false, searchable: false, },
{ targets: [0, 2, 4, 5, 6], type: 'html'}
],
initComplete: function () {
// initially the div which is a containter has opacity 0
$('#div_column_project').animate({ opacity: 1, }, { duration: 100, });
},
});
});
This is working well just sometimes. Often, the rows never appear and the DataTable shows the message:
No matching records found
Is there a way to do this better in order to avoid this asynchronous issue? I say asynchronous because apparently is random.
I have also tried to add this hack without good results. I think the problem is in the DataTable call where the table rows are removed
var _check_loaded_rows = setInterval(function() {
if ($('#table_column_project tbody tr').length == cols.length) { // check if all rows are correctly loaded
clearInterval(_check_loaded_rows);
$('#table_column_project').DataTable( { // TODO: show only when rendered
scrollY: 400,
scrollCollapse: true,
paging: false,
searching: true,
ordering: true,
order: [[ 1, 'asc' ]], // this is the value by default
info: false,
columnDefs: [
{ targets: '_all', visible: true, },
{ targets: [6], orderable: false, searchable: false, },
{ targets: [0, 2, 4, 5, 6], type: 'html'}
],
initComplete: function () {
$('#div_column_project').animate({ opacity: 1, }, { duration: 100, });
},
});
}
}, 100);
Actually, now I have a setTimeout with 500ms of delay to make it work well.
I have also read this answer where the poster recommends that we should use the bootstrap version, the table should be initialized (I use opacity to hide it, instead of display: none;) and to show the DataTable I use the builtin method initComplete to run the instruction to set the opacity.
If you just have a few hundred rows, why not insert them using the API in initComplete? You can pass the API to another function (like the one using get_* methods you already use to populate (it is unclear if it is a function or not)) :
function populate(api) {
for (var i = 0; i < cols.length; i++) {
...
api.row.add([cb_export, name, data_type, attrs, sel_cur_prec, txt_cur_unit, set_bt])
}
api.draw/()
}
$('#table_column_project').DataTable({
...
initComplete: function() {
const api = this.api()
populate(api)
}
})
Or, you can use a promise and wait for that inside the modal event handler:
function populate() {
return new Promise(resolve => {
...
if (i+1 === cols.length) resolve()
})
}
$('#column_project_win').on('shown.bs.modal', function (e) {
populate().then(() => {
$('#table_column_project').DataTable( {
...
})
})
})
If you not have Promise available in your nodejs (older versions) you can use for example es6-promise and
const Promise = require('es6-promise').Promise

JQgrid show message before update and multiple update

I am working on JQgrid and trying to achieve some specific functionality. These functionalists are
1)inline update with message shown before update.
2)Multiple update
I tried to read jqgrid and got this code https://jsfiddle.net/OlegKi/byygepy3/11/ . Which is quite approximate to my requirement but it doesn't contain multiple update and message shown before update.
I tried to overwrite these code but maximum i reached is this https://jsfiddle.net/byygepy3/72/ but failed because multiple update only updating half of record and it doesn't show any message before updating either single row or multiple row.
code is inserting just allow me to ask question.
$(function () {
var myData = [
{ id: 10, ParameterName: "Test", ParameterValue: "" },
{ id: 20, ParameterName: "Test 1", ParameterValue: "" },
{ id: 30, ParameterName: "Test 2", ParameterValue: "" },
{ id: 40, ParameterName: "Test 2", ParameterValue: "" },
{ id: 50, ParameterName: "Test 2", ParameterValue: "" },
{ id: 60, ParameterName: "Test 2", ParameterValue: "" }
],
$grid = $("#list");
// change the text displayed on editrules: {required: true }
$.extend(true, $.jgrid.locales["en-US"].edit.msg, {
required: "No value was entered for this parameter!!!"
});
$grid.jqGrid({
datatype: "local",
data: myData,
colNames: ["", "Parameter Name", "Parameter Value"],
colModel: [
{ name: "act", template: "actions" }, // optional feature
{ name: "ParameterName" },
{ name: "ParameterValue", editable: true,
editoptions: { maxlength: 100 }, editrules: {required: true } }
],
cmTemplate: { autoResizable: true },
autoResizing: { compact: true },
pager: true,
pgbuttons: false, // disable page control like next, back button
pgtext: null, // disable pager text like 'Page 0 of 10'
viewrecords: true, // disable current view record text like 'View 1-10 of 100'
sortname: "Name",
iconSet: "fontAwesome",
caption: 'Parameters',
autowidth: true,
hidegrid: false,
inlineEditing: {
keys: true
},
singleSelectClickMode: "selectonly", // prevent unselect once selected rows
beforeSelectRow: function (rowid) {
// allow selection if saving successful
},
onSelectRow: function (rowid) {
$(this).jqGrid("editRow", rowid);
},
afterSetRow: function (options) {
var item = $(this).jqGrid("getLocalRow", options.rowid);
if (item != null) {
item.dirty = true;
}
},
navOptions: {
edit: false,
add: false,
search: false,
deltext: "Delete",
refreshtext: "Refresh"
},
inlineNavOptions: {
save: false,
savetext: "Save",
cancel: false,
restoreAfterSelect: false
},
formDeleting: {
// delete options
url: window.g_baseUrl + 'MfgTransactions_MVC/COA/Delete?',
beforeSubmit: function () {
// get value
var selRowId = $(this).jqGrid('getGridParam', 'selrow');
var parametricValue = $(this).jqGrid('getCell', selRowId, 'ParameterValue');
// check if empty
if (parametricValue === "") {
return [false, "Cannot delete: No value exists for this parameter"];
}
return [true, "Successfully deleted"];
},
delData: {
batchId: function () {
return $("#BatchId").val();
}
},
closeOnEscape: true,
closeAfterDelete: true,
width: 400,
msg: "Are you sure you want to delete the Parameter?",
afterComplete: function (response) {
if (response.responseText) {
alert("response.responseText");
}
//loadBatchListIntoGrid();
}
}
}).jqGrid('navGrid')
.jqGrid('inlineNav')
.jqGrid('navButtonAdd', {
caption: "Save Changed",
buttonicon: "fa-floppy-o",
onClickButton: function () {
var $self = $(this), i,
// savedRows array is not empty if some row is in inline editing mode
savedRows = $self.jqGrid("getGridParam", "savedRow");
for (i = 0; i < savedRows.length; i++) {
$self.jqGrid("saveRow", savedRows[i].id);
}
var localData = $(this).jqGrid("getGridParam", "data"),
dirtyData = $.grep(localData, function (item) {
return item.dirty;
});
alert(dirtyData.length > 0 ? JSON.stringify(dirtyData) : "no dirty data");
}
});
// make more place for navigator buttons be rwducing the width of the right part
var pagerIdSelector = $grid.jqGrid("getGridParam", "pager");
$(pagerIdSelector + "_right").width(100);
// make the grid responsive
$(window).bind("resize", function () {
$grid.jqGrid("setGridWidth", $grid.closest(".container-fluid").width());
}).triggerHandler("resize");
});
Free jqGrid supports a lot of callbacks, which will be used during saving the rows. You can use for example beforeSaveRow callback of inline editing, custom validation via editrules.custom callback function, beforeSelectRow and other. Additionally, your code seems to distinguish the initial empty value "" of ParameterValue column from any other values. The final code you should made yourself. I posted an example
beforeSelectRow: function (rowid) {
// allow selection if saving successful
var $self = $(this), i,
savedRows = $self.jqGrid("getGridParam", "savedRow");
for (i = 0; i < savedRows.length; i++) {
if (rowid !== savedRows[i].id) {
if (allowSaving.call(this, savedRows[i].id)) {
$self.jqGrid("saveRow", savedRows[i].id);
} else {
$self.jqGrid("restoreRow", savedRows[i].id);
}
}
}
return true;
},
with allowSaving function defined as
var allowSaving = function (rowid) {
var item = $(this).jqGrid("getRowData", rowid);
if (item.ParameterValue !== "") {
return confirm("Do you want to save \"" +
item.ParameterValue + "\" value in \"" +
item.ParameterName + "\"?");
} else {
return false;
}
};
It allows to ask the user to confirm the changes of ParameterName. Additionally the code of "Save Changed" button should be adjusted too.
See https://jsfiddle.net/OlegKi/byygepy3/74/

The cell in jsGrid had not being updated

i am working on lightswitch project ,and I am using JsGrid.I ran into one problem and I don't couldn't find the solution.here is the scenario:
I use the grid to get data from database table,when I update one of the cell It's value doesn't appear unless I click on the cell again,and if I update it in the second time then the new value appear.
I tried to refresh the grid after itemupdated but still the new value doesn't appear instantaneously.my code is here:
$("#jsGrid").jsGrid({
width: "100%",
height: "auto",
inserting: true,
editing: true,
sorting: true,
paging: true,
autoload: true,
controller: {
loadData: function () {
var deferred = jQuery.Deferred();
myapp.activeDataWorkspace.ApplicationData.Table1Items.load().done(function (data) {
deferred.resolve(data.results);
});
return deferred.promise();
},
updateData: function () {
$("#jsGrid").jsGrid("refresh");
},
deleteItem: function (Item) {
$("#jsGrid").jsGrid("refresh");
}
},
fields: [
{ name: "EmployeeName", type: "text", width: 150 },
{ name: "Points", type: "text", width: 200 },
{ type: "control", editButton: true, // show edit button
deleteButton: true, // show delete button
clearFilterButton: true, // show clear filter button
modeSwitchButton: true // show switching filtering/inserting button
}]
,
onItemInserted: function (item) {
}, onItemUpdating: function (item) {
$("#jsGrid").jsGrid("refresh");
},
onItemUpdated: function (item)
{
$("#jsGrid").jsGrid("refresh");
console.log("it is updated", item.item);
$("#jsGrid").jsGrid("refresh");
}
});
your help is invaluable and many thanks in advance.
hope this may help you. updateItem is a function returning updated item or jQuery promise that will be resolved with updated item. Accepts updating item object.
on successful updating Item, use
updateItem: function(item) {
return $.ajax({
type: "PUT",
url: "/items",
data: item
});
},
if you have any queries, comment below.
fore more details : see link

Categories

Resources