Retrieve returns from another JavaScript file - javascript

I've created a HTML file in PAGE directory called Test-Page-1.html. And in the root, I've a JavaScript file called Script.Con.js.
In the html file, I have this script:
(function Flush () {
var Customer = {
name: prompt("Your Name?"),
id: 10100
product_bought: prompt("What is it you want?"),
d_o_d_expected: prompt("When do you expect it?")}
return "name: " + Customer.name + "\n" +
"id: " + Customer.id + "\n" +
"product: " + Customer.product_bought + "\n" +
"expected on: " + Customer.d_o_d_expected;
})
/** FORGIVE THE CODE'S CLUMSINESS **/
I want Script.Con.js to get the value returned by the Flush() function. I don't know how to do this, please help me out. Thanks in advance.

You can include var statement before calling IIFE by including () before or following last closing parenthesis to set identifier for value returned by IIFE
<script>
var result = (function Flush () {
var Customer = {
name: prompt("Your Name?"),
id: 10100, // missing `,` here
product_bought: prompt("What is it you want?"),
d_o_d_expected: prompt("When do you expect it?")}
return "name: " + Customer.name + "\n" +
"id: " + Customer.id + "\n" +
"product: " + Customer.product_bought + "\n" +
"expected on: " + Customer.d_o_d_expected;
}()); // `result` should be accessible by `Script.Con.js`
</script>
<script src="Script.Con.js"></script>

The way that's written, your Script.Con.js file's code can't call Flush — and neither can anything else, you've used a named function expression to create a function you never keep any reference to. NFEs don't even add the name to the current scope, so nothing can ever refer to that function.
You have a couple of options:
Make it a function declaration instead by removing the () around it, and then have Script.Con.js call it:
function Flush () {
var Customer = {
name: prompt("Your Name?"),
id: 10100 ,
product_bought: prompt("What is it you want?"),
d_o_d_expected: prompt("When do you expect it?")}
return "name: " + Customer.name + "\n" +
"id: " + Customer.id + "\n" +
"product: " + Customer.product_bought + "\n" +
"expected on: " + Customer.d_o_d_expected;
}
Then in Script.Con.js:
var order = Flush();
Note that the prompts won't happen until Script.Con.js calls Flush().
Run it immediately and save the result in a variable, then have Script.Con.js use the variable:
var order = (function Flush () {
var Customer = {
name: prompt("Your Name?"),
id: 10100 ,
product_bought: prompt("What is it you want?"),
d_o_d_expected: prompt("When do you expect it?")}
return "name: " + Customer.name + "\n" +
"id: " + Customer.id + "\n" +
"product: " + Customer.product_bought + "\n" +
"expected on: " + Customer.d_o_d_expected;
})();
Note the () at the end to actually call it. That will trigger the prompts immediately, and save the result to order. Then your Script.Con.js code would use the order variable directly.
Side Note: The overwhelming convention in JavaScript is that non-constructor functions like this start with a lowercase letter, e.g. flush rather than Flush. (Also a bit confused about the name "flush" but...)
Side Note 2: You were missing a , after id: 10100. Added above.

Related

Concat QML Properties with Javascript

I'm setting properties on QML items with java script, where "gaugetext" is a property of my QML object.
function finishCreation(setWidth,setHeight,setX,setY,setMinValue,setMaxValue,setDecPlace,setUnit,setID,SetValueObject,SetValueProperty) {
...
"gaugetext": Qt.binding(function(){return SetValueObject[SetValueProperty] + " " + setUnit})
....
}
This works well, but I want to set numbers of decimals. So I tried this:
"gaugetext": Qt.binding(function(){return "(" + SetValueObject[SetValueProperty]+ ")" + ".toFixed(" + setDecPlace + ")" + " " + setUnit})
But this results that the correct Value is shown with ".toFixed(value)".
You return a String "(<someValue>).toFixed(<someOtherValue>) <someThirdValue>".
You probably want to omit some of your " since you probably want to have the pieces that you mark as string to be executed instead.
return SetValueObject[SetValueProperty].toFixed(setDecPlace) + " " + setUnit
~~~(untetested)
Most likely however using a "finalize creation" function is a bad approach.

Using javascript function argument to return object value

Javascript function that takes a single argument. Use that argument value which is a string to return the appropriate value from the matched object key.
function someFunction(someArg) {
var message = {
bob: "Hello bob",
mike: "Hello mike",
tara: "Hello tara"
}
console.log(message + " " + message.someArg + " " + someArg + " " + message.bob);
}
what is returned is
[object Object] undefined bob Hello bob
Where undefined is returned in the console log, JavaScript should return the message "Hello bob" as the value of someArg is "bob", calling message.bob returns the correct result.
To print it properly, you'll have to:
Stringify the message object
Refer to the property of message in a correct manner
Try this
function someFunction(someArg) {
var message = {
bob: "Hello bob",
mike: "Hello mike",
tara: "Hello tara"
}
//ES6
console.log(`${JSON.stringify(message)} ${message[someArg]} ${someArg} ${message.bob}`);
//ES5
console.log(JSON.stringify(message) + " " + message[someArg] + " " + someArg + " " + message.bob);
}
Now, on calling someFunction('bob'), the output is:
{"bob":"Hello bob","mike":"Hello mike","tara":"Hello tara"} Hello bob bob Hello bob
When using message.someArg you are "telling" attribute someArg or your message Object.
What you have to use is message[someArg] to get the dynamic property.
You have to use the [] notation, where obj[key] is the same as obj.key, but key can be a variable.
function someFunction(someArg) {
var message = {
bob: "Hello bob",
mike: "Hello mike",
tara: "Hello tara"
}
console.log(JSON.stringify(message) + " " + message[someArg] + " " + someArg + " " + message.bob);
}
someFunction("mike");

Returning a concatenated string from a functions' properties in javascript

I'm a total JS beginner. Here is the JsBin link formLetter test should be passing.
TL;DR
This:
var formLetter = function(recipient, msg, sender) {
return "Hello " + recipient + ",\n" + "\n" + msg + "\n" + "\nSincerely," + "\n" + sender
};
console.log(formLetter("Hermione", "Luna","How are you?"));
Should return:
"Hello Hermione,
How are you?
Sincerely,
Luna"
But instead I get this:
"Hello [object Object],
undefined
Sincerely,
undefined"
Edit
Sorry for the confusion. I'm working on different problems inside one JsBin. This is the correct JsBin with the isolated code.
This is because you are only getting one object passed into the function call. This object contains the information you need in lieu of the named arugments you have provided.
The first argument, recipient being [object Object] tells you that it's an object. undefined means that nothing was passed in their place. This signifies the common pattern of a config or param object being passed to the function call. Because of this, what you have as named arguments should really be property look ups on the object provided as the first argument.
Your function definition should look more like:
var formLetter = function (letter) {
// do something with letter
};
Inside of that function call, you may then hit the properties of the letter object to see if they contain what you need, Doing console.log debugging in dev tools will help track it down.
The line:
var formLetter = function(recipient, msg, sender) {
return "Hello " + recipient + ",\n" + "\n" + msg + "\n" + "\nSincerely," + "\n" + sender
};
in your example needs one semicolon after "sender", like:
var formLetter = function(recipient, msg, sender) {
return "Hello " + recipient + ",\n" + "\n" + msg + "\n" + "\nSincerely," + "\n" + sender;
};
Your undefined is related to the use of anidated console.log.
You do:
console.log(longMessage.formLetter("Hermione", "Luna","How are you?"));
and (in the JsBin) you have also:
var longMessage = {
formLetter: function(recipient, sender, msg) {
console.log("Hello " + recipient + ",\n" + "\n" + msg + "\n" + "\nSincerely," + "\n" + sender);
}
};
In the example of your question you have them corrected.
Double check the code you post, please.
After looking at your test in jsbin, I noticed that in your assert.deepEqual() method you run formLetter(letter) and compares it to the concatenated string you created.
The problem is that formLetter() expects three string values and you send it an object (letter). That's why you get [Object object] in the first location and undefined in the others.
You should run formLetter(letter.recipient, letter.msg, letter.sender) in your assert and it should work properly.

binding variables to SQL statements using node-sqlite3

I am trying to convert this:
var query_string = 'SELECT protein_A, protein_B, PIPE_score, site1_A_start FROM ' + organism + PIPE_output_table +
' WHERE ' + score_type + ' > ' + cutoff['range'] + ' AND protein_A = "' + item + '" ' +
'UNION SELECT protein_A, protein_B, PIPE_score, site1_A_start FROM ' + organism + PIPE_output_table +
' WHERE ' + score_type + ' > ' + cutoff['range'] + ' AND protein_B = "' + item + '";';
db.each(query_string, function (err, row) {
...
To this:
var query_string = "SELECT protein_A, protein_B, PIPE_score, site1_A_start FROM $table WHERE $score_type > $score AND protein_A = '$protein'" +
" UNION SELECT protein_A, protein_B, PIPE_score, site1_A_start FROM $table WHERE $score_type > $score AND protein_A = '$protein'";
var placeholders = {
$table: organism + PIPE_output_table,
$score_type: score_type,
$score: cutoff['range'],
$protein: item
};
var stmt = db.prepare(query_string, placeholders, function(err) {
console.log(err);
stmt.each(function(err,row) {
...
})
}
but I keep getting this error:
Error: SQLITE_ERROR: near "$table": syntax error
But I am not sure what is syntactically wrong here since the format is as I have seen it in the API documentation. I have tried '?', '#', and ':' before each variables but none seem to be recognized.
What's wrong in my code?
Bind parameters only work for values in the WHERE clause. Table and column names (collectively called "identifiers") won't work.
"SELECT foo FROM bar WHERE this = $that" # OK
"SELECT foo FROM bar WHERE $this = 'that'" # Not OK
Normally you'd work around this by escaping and quoting identifiers and inserting them into the query. A good database library has a method call for this...
var this = db.quote_literal(input_column);
'SELECT foo FROM bar WHERE ' + this + ' = ?'
Unfortunately, node-sqlite3 doesn't appear to have one. :(
SQLite does provide a quoting function, the %w operator, but node-sqlite3 doesn't appear to make it available.
You'll have to write your own. Follow the instructions from this answer in Python and convert them to Javascript.
Ensure the string can be encoded as UTF-8.
Ensure the string does not include any NUL characters.
Replace all " with "".
Wrap the entire thing in double quotes.
I'm not very good with Javascript, so I'll leave you to code that.

Pass multiple parameters from ASP.NET to javascript function

Essentially what I'm trying to do is fairly simple....pass more than one parameter (4 total eventually) into a javascript function from my ASP.NET code behind.
What I've tried to do is this in the ASCX file...
function ToggleReportOptions(filenameText, buttonText) { /*stuff happens here*/ }
and this in the ASCX.cs file...
string testing123 = "testStringOne";
string testing124 = "testStringTwo";
optReportOptionsRunRealTime.Attributes["onClick"] = "ToggleReportOptions('" + testing123 + ", " + testing124 + "')";
optReportOptionsOffline.Attributes["onClick"] = "ToggleReportOptions('" + testing123 + ", " + testing124 + "')";
but this doesn't seem to work as in my output the first variable contains "testStringOne, testStringTwo" and the 2nd variable is "undefined"
Any help on clearing up my probably stupid issue here would be great (i'm very inexperienced with javascript, more of a .NET developer)
You've missed out a few single-quotes, meaning that you're passing a single string containing a comma rather than two separate strings. That is, you're passing 'testStringOne, testStringTwo' rather than 'testStringOne' and 'testStringTwo'.
Try this instead:
optReportOptionsRunRealTime.Attributes["onClick"] =
"ToggleReportOptions('" + testing123 + "', '" + testing124 + "')";
optReportOptionsOffline.Attributes["onClick"] =
"ToggleReportOptions('" + testing123 + "', '" + testing124 + "')";

Categories

Resources