coffeescript return - javascript

I have this piece of javascript:
if(this.isShown || event.isDefaultPrevented()){
return;
}
And I tried to convert it into Coffeescript but I can't seem to get the null return to work:
if #isShown or event.isDefaultPrevented()
return;
How can I get it working properly?

It appears that the CoffeeScript compiler won't implicitly return null unless it needs to to prevent later code from executing. If something happend after that code, it would add the null return, e.g.:
if #isShown or event.isDefaultPrevented()
return
alert(1)
// compiles to =>
if (this.isShown || event.isDefaultPrevented()) {
return;
}
alert(1);
Whereas in your case above, the function would just exit anyway after the conditional, rendering a null return unnecessary.

You're problem must lie elsewhere... I went to http://coffeescript.org, clicked 'try it', and pasted in your CS code. The JS it generated matches your original JS code.
CoffeeScript error messages often don't actually mean what they say. That's what makes it so much fun... you get be a detective but without having to quit your job as a programmer! Post a larger code block and maybe we can help you with your detective work.

Related

Blockly - Reference Error: functions not defined

I'm attempting to use Blockly to do a "make your own game" sort of thing, and for the most part it works. However, when trying to run code generated (by Blockly's own pre-defined function generators) by declaring a function and calling it, I consistently get told that the function isn't defined, no matter what it is or what it contains.
I'm grabbing and running the code like so:
var code = Blockly.JavaScript.workspaceToCode();
try{
eval(code);
} catch (e){
alert(e);
}
Which is how the demos provide on Blockly generate code. I've also echoed the code out elsewhere in the page and it looks right to me:
function whatINameIt() {
//code I give it
}
//rest of code
Is this something to do with how eval works? The only thing I can think of is that for some reason it's "evaluating" the function code but not adding it as something callable. If that's the case, is there an alternate way I should run the code string Blockly gives me?
Maybe you are creating an infinite loop. To solve it, you will have to add the following lines as the documentation of Blockly says:
window.LoopTrap = 1000;
Blockly.JavaScript.INFINITE_LOOP_TRAP = 'if(--window.LoopTrap == 0) throw "Infinite loop.";\n';
var code = Blockly.JavaScript.workspaceToCode(workspace);
Also, if you have created custom Blocks, as it seems in your question, make sure that you are returning the code that you are creating in all of them. If you do not return it, the workspace will not know that these Blocks want to do whatever.
It would be great to help you if you provide the Blocks code that you are creating/using and the code that you are retrieving from your other function.

null for elements in phantomjs

I have this code running in the phantomjs. I don't know why form.elements keeps returning null to me. I ran the same code on chrome developer console and got the right result i want.
I'm pretty new to javascript and everything related. Please shed some light.
var page = require('webpage').create();
page.open('http://www.kayak.com', function (status) {
if (status !== 'success') {
console.log('Unable to access network');
} else {
var form = page.evaluate(function(){
return document.getElementById('searchform');
});
console.log(form.elements[2].value);
}
phantom.exit();
});
You can't pass a non-primitive object through evaluate. This is mentioned in the documentation:
Note: The arguments and the return value to the evaluate function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine. Closures, functions, DOM nodes, etc. will not work!
Although it is the most common mistake when using PhantomJS, this is rather easy to solve. Just make sure you do all the processing as much as you can within evaluate and then return back a simple object. For details, please study the documentation carefully and learn from all the included examples.

Javascript - Reaction to unvalid eval()

I'm making a calculator in Javascript for my school homework and it's using the function eval(). Yes, I know, eval is evil, but I can assure you that I already secured this, so there's no way of exploiting it.
The eval turns the value in textbox into an answer, which is then displayed in another textbox. However, when the syntaxe is wrong (for example, user enters "1++2") I would like if the script displayed some kind of error. But eval() just seems to disappear when the input is unvalid. It returns no value, no error (well, chrome tries explaining it with 'Uncaught Syntaxerror', but that is no use for me) so I have no way to explain to the script what to do, if user messes up the syntaxe.
TL;DR: How do I make the script display an error message, if the eval() has unvalid input?
Thanks in advance
It throws (raises) an exception, which you can catch (handle) and do whatever you want with:
var s;
try
{ s = eval('1++2'); }
catch(e)
{ s = e; }
// now s is either the result, or the exception-info
You should use a try catch block to gracefully show the user that an error has occured.
function evalJS(JsCode)
{
try
{
eval(JsCode);
}
catch(e)
{
alert('The string ' + JsCode + ' contained incorrect JS syntax.');
}
}
evalJS('bogus code');

js function not running on page load?

I apologize for this rather BASIC question, but I am at whits end here!
I have a javascript function that I want to run when the page loads... simple right? I have tried putting the function in doc readys, window readys, putting it before and after the main function, etc etc. NOTHING seems to work.
Code so far:
function calcme() {
DA FUNCTON
}
$(document).ready(function(){
calcme();
$("input").bind("keyup", calcme);
});
Please note... the keyup bind DOES work, but I need the calcme function to load on page load. Thoughts?
UPDATE: As per request, here is the full fiddle. http://jsfiddle.net/vpsSA/
Problem found: The calcme() function assumes it is called from the context of one of the inputs and uses this.value inside. So, when you call it without any arguments, it obviously fails. This can be solved by trigger the keyup of each of your inputs, instead of calling calcme() directly. See the fiddle below.
Working fiddle: http://jsfiddle.net/vpsSA/1/
In your ready() handler, the bind statement comes after the caclme() call. And as you mentioned the event binding worked. This means:
a) calcme() was definitely executed on load. There is no other way since you've mentioned that the binding statement which comes after the calcme() call worked as expected.
b) calcme() did not throw any JS errors - if so, it would have stopped at the error and the event binding would not have taken place. Maybe it threw a warning, which you'll be able to see in your JS console.
c) Since you haven't provided whats inside calcme(), we can't say for sure. But what it looks like is some sort of condition failure because of which you did not get the expected result from calcme() when running on load. Are you using anything inside calcme() thats initialized after running it on load. I would suggest putting in a debugger; statement as the first line in your ready() handler and tracing it in Firebug or Chrome.
try this:
function calcme() {
try {
//your code
}
catch(e) {
alert('error: ' + e);
}
}
if (typeof $ === undefined)) {
alert('not jquery');
}
$(document).ready(function(){
if (typeof calcme === undefined) {
alert('calcme not exist');
}
else {
calcme();
$("input").bind("keyup", calcme);
}
});

call function using if statement

I want to be able to call a function within an if statement.
For example:
var photo = "yes";
if (photo=="yes") {
capturePhoto();
}
else {
//do nothing
};
This does nothing though. The function is clearly defined above this if statement.
Edit: Wow, downboated to hell! capturePhoto(); was just an example function that didn't really need any more explanation in this scenario?
That should work. Maybe capturePhoto() has a bug?
Insert an alert() or console.log():
var photo = "yes";
if (photo == "yes") {
alert("Thank you StackOverflow, you're a very big gift for all programmers!");
capturePhoto();
} else {
alert("StackOverflow.com must help me!");
}
I'm not seeing any problems here. I used this code and the function call worked. I kept your code and just added a function called capturePhoto().
Are you sure that the code you're using to call the function is firing?
var photo = "yes";
if (photo=="yes")
{
capturePhoto();
}
else
{
//do nothing
};
function capturePhoto()
{
alert("Pop up Message");
}
You probably missed something, a quotation, a semicolon or something like that. I would recommend you to use a debugger like Firebug or even Google Chrome's Web Developer Tool. You will know what's wrong with your code and where it is wrong.
You may take a look at this live code that your code above works: http://jsfiddle.net/ZHbqK/
The code looks fine to me (except you don't need the ; at the end of the last line). Check your error log; perhaps the browser thinks capturePhoto is not defined for some reason. You can also add alert statements to make sure the code is actually running:
var photo = "yes";
alert('Entering if statement');
if (photo=="yes") {
alert('then');
capturePhoto();
} else {
alert('else');
//do nothing
}
When you encounter a situation where it seems like a fundamental language feature is not working, get some more information about what is going on. It is almost never the platform's fault. It is occasionally a misunderstanding of how the feature works (e.g. why does parseInt('031') == 25 ?). It is usually a violation of an assumption you're making about the code that isn't holding up because of a problem elsewhere.
You should also consider using true and false instead of strings that could be manipulated depending on input.
If I had to correct the following code, then I should've done it like this;
var photo = true; // Will capture picture.
if (photo) { // 'true' is a truthy value.
capturePhoto();
} else {
// Do nothing
}
The code that you posted does work.
I copied it and tested it.
Demo: http://jsfiddle.net/Guffa/vraPQ/
The only thing wrong with it that I can see is a semicolon after the closing bracket, but that is only a style problem. It will form an extra empty statement, but that doesn't cause any problems.

Categories