How to define this variable below? - javascript

I have a Cancel button which appears when the user is uploading a file. If the user wishes to cancel a file upload then they can by clicking on the Cancel Button and it would display the cancel message to user.
The only problem when attempting this is that it is stating that cancel_image_file_name is undefined in the stopImageUpload function where I want to display the message. But I did define this in the startImageUpload function. So my question is that how can I grab cancel_image_file_name from the startImageUpload function and define it in the stopImageUpload function?
Below is the code showing the 2 functions:
startImageUpload function:
var cancelimagecounter = 0;
function startImageUpload(imageuploadform, imagefilename){
cancelimagecounter++;
var _cancelimagecounter = cancelimagecounter;
$('.imageCancel').on("click", function(event) {
var cancel_image_file_name = $(this).attr('cancel_image_file_name');
return stopImageUpload(2, cancel_image_file_name);
});
return true;
}
stopImageUpload function:
var imagecounter = 0;
function stopImageUpload(success, imagefilename){
var result = '';
imagecounter++;
if (success == 1){
result = '<span class="imagemsg'+imagecounter+'">The file was uploaded successfully!</span><br/><br/>';
$('.listImage').eq(window.lastUploadImageIndex).append('<div>' + htmlEncode(imagefilename) + '<button type="button" class="deletefileimage" image_file_name="' + imagefilename + '">Remove</button><br/><hr/></div>');
}
else if (success == 2){
result = '<span class="imageemsg">' + cancel_image_file_name + ' Upload Was Cancelled!</span><br/><br/>';
}
else {
result = '<span class="imageemsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}

In JavaScript variables have function-level scope, to get cancel_image_file_name in your other function too, define it outside of both functions.
BTW, you can use imagefilename from your stopImageUpload function because you are already passing it to that function:
return stopImageUpload(2, cancel_image_file_name);
So in your stopImageUpload function, change line:
result = '<span class="imageemsg">' + cancel_image_file_name + ' Upload Was Cancelled!</span><br/><br/>';
To:
result = '<span class="imageemsg">' + imagefilename + ' Upload Was Cancelled!</span><br/><br/>';

You're already passing in the value as the second parameter to "stopImageUpload", "imagefilename". Just use that.
In fact elsewhere in that same function you're using the parameter.

Restructure your code like this:
(function() {
var cancelimagecounter = 0,
imagecounter = 0,
cancel_image_file_name;
window.startImageUpload = function(imageuploadform,imagefilename) {
...
cancel_image_file_name = ... // (remove the var)
...
};
window.stopImageUpload = function(success,imagefilename) {
...
// cancel_image_file_name is not undefined now.
};
})();

Related

Call variable value in another .js file

I have 2 soy.js and lib-dialogs.js files.
I need to make lib-dialogs pass the value of the lineCount variable to soy.js.
I was able to do this with localStorage but because it saves in a cookie it does not update the values correctly.
In lib-dialogs there is a function called BlocklyDialogs.congratulations that calls the necessary data.
FIle:lib-dialogs.js
BlocklyDialogs.congratulations = function() {
// Add the user's code.
if (BlocklyGames.workspace) {
var linesText = document.getElementById('dialogLinesText');
linesText.textContent = '';
// Line produces warning when compiling Puzzle since there is no JavaScript
// generator. But this function is never called in Puzzle, so no matter.
var code = Blockly.JavaScript.workspaceToCode(BlocklyGames.workspace);
code = BlocklyInterface.stripCode(code);
var noComments = code.replace(/\/\/[^\n]*/g, ''); // Inline comments.
noComments = noComments.replace(/\/\*.*\*\//g, ''); /* Block comments. */
noComments = noComments.replace(/[ \t]+\n/g, '\n'); // Trailing spaces.
noComments = noComments.replace(/\n+/g, '\n'); // Blank lines.
noComments = noComments.trim();
var lineCount = noComments.split('\n').length;
var pre = document.getElementById('containerCode');
pre.textContent = code;
if (typeof prettyPrintOne == 'function') {
code = pre.innerHTML;
code = prettyPrintOne(code, 'js');
pre.innerHTML = code;
}
if (lineCount == 1) {
var text = BlocklyGames.getMsg('Games_linesOfCode1');
} else {
var text = BlocklyGames.getMsg('Games_linesOfCode2')
.replace('%1', String(lineCount));
}
linesText.appendChild(document.createTextNode(text));
}
FIle:soy.js
example "var count = BlocklyDialogs.congratulations(lineCount);"
In soy.js I need to receive the values of lineCount. I've already managed to do this using localStorage but I needed to do something more direct.
In testing I verified that the problem is in the lineCount variable because it is not passing a value to any variable even within the file itself.
I created a variable outside the blocklyDialogs.congratulations function and entered a value of 5.
I called the variable in the soy.js file and got it normally.
I need to make the lineCount pass its value.
You can use event driven programming, pub-sub model.
class EventManager {
constructor(...listeners) {
this.listeners = listeners;
}
register(fn) {
const id = this.listeners.push(fn);
return () => {
this.listeners.splice(id - 1, 1);
};
}
emit(data) {
this.listeners.forEach(fn => fn(data));
}
}
const pushEvents = new EventManager();
// JS 1
const unsubscribe1 = pushEvents.register(x => {
console.log("event:", x);
});
pushEvents.register(x => {
console.log("event:", x);
});
// JS 2
pushEvents.emit("Tets data");
//Output
// event: Tets data
// event: Tets data
unsubscribe1();
pushEvents.emit("Tets data2");
//Output
// event: Tets data2
.as-console-row {color: red!important}

Nightwatch variable scope and accessing outside .element call

I have the following method in my Nightwatch test that does not work as expected:
function checkCategoryRows(browser, theOptionText, rows) {
var isGood = true;
rows.value.forEach(function (row) {
browser.elementIdText(row.ELEMENT, function (categoryText) {
if (categoryText.value != theOptionText) {
browser.verify.ok(0 == 1, categoryText.value + ' = ' + theOptionText);
isGood = false;
} else
isGood = false; //<-- Manually making sure it sets either way
})
})
browser.verify.ok(isGood == true, theOptionText + ' category is good...');
}
isGood
is always true; even if I set it manually. It appears that anything inside the browser.element(){} call is only scoped inside that call.
How do I get this to work so at the end of the for loop I can show that something was 'not good' in that particular set of rows?
Apparently, in Nightwatch, there is no 'document' or 'window' object. There is a 'browser' object that seems to be similar. Here is how I solved it:
function checkCategoryRows(browser, theOptionText, rows) {
browser.isGood = true;
rows.value.forEach(function (row) {
browser.elementIdText(row.ELEMENT, function (categoryText) {
//console.info(categoryText)
if (categoryText.value != theOptionText) {
browser.verify.ok(0 == 1, categoryText.value + ' = ' + theOptionText);
browser.isGood = false;
}
//else
// browser.isGood = false; // for testing
console.log('browser.isGood=' + browser.isGood);
})
})
browser.verify.ok(browser.isGood == true, theOptionText + ' category is good...');
}
Setting browser.isGood = true; initially made it available to the rest of the method.

Pass Variables in Url in Framework7 Inside Pages

I am new to Framework7.io. I have got the following script which fetches the data from sqlite based on the parameters passed in the url.
However all the Js is called in index.html (the first page of F7), whereas I have get parameters in the inside pages.
code in b.html
<a href="a.html?type=new&ok=fine" >Go to a with values of ok & type</a>
code in a.html
function getParameterValue(type) {
type = type.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + type + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var type1 = getParameterValue('type');
Update:
Currently using this code with no successs.
$$(document).on('page:init', function (e) {
var page = e.detail.page;
myApp.alert(page);
if (page.name === 'a') {
var count = page.query.count;
myApp.alert(count);
// Now we can generate some dummy list
var listHTML = '<ul>';
for (var i = 0; i < count; i++) {
listHTML += '<li>' + i + '</li>';
}
listHTML += '</ul>';
// And insert generated list to page content
$$(page.container).find('.page-content').append(listHTML);
}
// Code for Services page
if (page.name === 'inch') {
myApp.alert('Here comes our inch!');
}
});
Thanks for your time and any help is highly appreciable.
Use page.query.your_url_parameter to get the parameter value.
Example:
To get <a href="a.html?type=new&ok=fine" >Go to a with values of ok & type</a> parameter :
$$(document).on('page:init', function (e) {
var page = e.detail.page;
if (page.name === 'a') {
var type = page.query.type; // returning "new"
var ok = page.query.ok; // returning "fine"
alert(type);
alert(ok);
}
// Code for Services page
if (page.name === 'inch') {
myApp.alert('Here comes our inch!');
}
});
Please see the documentation

Use a javascript var in function - order issue

I am having issues with the order of my javascript, I'm sure this is very easy:
I want to check what a variable is (using an if statement), and then set it either from another var, or from the value in a txt file
So far I can load the file, and set the var (I can check it in the console) successfully
However the later parts of the script do not wait for the var to be set, so the var is not used, resulting in an error for the var "cleanTradeDate"
My question is, is the below correct or should I be structuring the var differently. How do I make the subsequent code wait/use the "cleanTradeDate" value?
Here is a sample of the code:
var URLTradeDate = document.URL.substring(document.URL.search('tradeDate=') + 10, document.URL.search('tradeDate=') + 22);
var cleanTradeDate;
$(document).ready(function () {
if (URLTradeDate == '') {
$.get('data/0.max_trade_date.txt', function(maxTradeDate) {
cleanTradeDate = maxTradeDate.replace(/[\n\r]+/g, '');
});
} else {
cleanTradeDate = URLTradeDate;
}
$("#datepicker").datepicker({dateFormat: 'yy-mm-dd'});
$("#datepicker").datepicker('setDate', cleanTradeDate);
});
It's not where the variable is declared, but that it's filled asynchronously. You better use promises:
$(document).ready(function () {
var index = location.search.indexOf('tradeDate=');
var URLTradeDate = location.search.slice(index + 10, index + 22);
var promise = (index == -1 || URLTradeDate == '')
? $.get('data/0.max_trade_date.txt').then(function(maxTradeDate) {
return maxTradeDate.replace(/[\n\r]+/g, '');
});
: $.when(URLTradeDate);
promise.then(function(cleanTradeDate) {
$("#datepicker").datepicker({dateFormat: 'yy-mm-dd'});
$("#datepicker").datepicker('setDate', cleanTradeDate);
});
});
$.get is asynchronous (meaning the code doesn't wait for it to finish before carrying on), so you'll want something more like:
var URLTradeDate = document.URL.substring(document.URL.search('tradeDate=') + 10, document.URL.search('tradeDate=') + 22);
$(document).ready(function () {
if (URLTradeDate == '') {
$.get('data/0.max_trade_date.txt', function(maxTradeDate) {
setTradeDate(maxTradeDate);
});
} else {
setTradeDate(URLTradeDate);
}
});
function setTradeDate(tradeDate){
tradeDate = tradeDate.replace(/[\n\r]+/g, '');
$("#datepicker").datepicker({dateFormat: 'yy-mm-dd'});
$("#datepicker").datepicker('setDate', tradeDate);
}
This way once the data is received from the $.get, you call a function 'setTradeDate' that sets the datepicker.
EDIT: moved the formatting of maxTradeDate inside the setTradeDate function and fixed a couple of errors I noticed.

listbox does not pass string to google script

When I select a user from listbox, the onChange() event triggers a function. It should pass a string to the function. Then the code finds the user's password and returns it for comparison. The following is the code which works fine if I hard code the user value, but not when I select it from the listbox.
function addClients(clients){
$('#customer').empty();
$('#customer').append('<option> ---- Choose a user ----</option>');
for (var i in clients) {
$('#customer').append('<option>'+clients[i]+'</option>');
$('#customer').trigger("chosen:updated");
}
}
getval function:
function getval(sel){
var usrpass = google.script.run.getuserpass(sel.value);
alert(usrpass);
}
the function in code.gs is as follows
function getuserpass(userval){
var usrpass = "";
var doc = SpreadsheetApp.openById("spreadsheet id");
var sheet = doc.getActiveSheet();
var data = sheet.getRange(3, 3, sheet.getLastRow(),5).getValues();;
for(n=0;n<data.length;++n){
// iterate row by row and examine data in column A
if(data[n][0].toString().match(userval)==userval){ usrpass = data[n][4]};
}
return usrpass;
}
Why does the return value come back as undefined rather than the password.
If I hardcode username in the function and run the function, then the return value is the value in the fifth column.
Try structuring the code like this:
<script>
function onSuccess(returnVal) {
alert('Success! ' + returnVal);
};
function getval(sel){
var selectValue = sel.value;
console.log('selectValue: ' + selectValue);
google.script.run
.withSuccessHandler(onSuccess)
.getuserpass(sel.value);
};
</script>
You can iterate through the object to see what is really in it, as a debugging test.
for (var propertyVal in sel) {
console.log('this property: ' + propertyVal);
console.log('this value: ' + sel[propertyVal]);
};
And see what is really in the object.

Categories