Blockly - Reference Error: functions not defined - javascript

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.

Related

Why getting "Uncaught ReferenceError: $ is not defined" error on Chrome Dev Console?

I'm trying to run a simple JQuery script in Chrome Developer Console but I have a problem.
There is no problem in this code when I run it on Chrome Developer Console:
var someValue = $("[name='Jack']");
if(someValue !== null){
console.log("Jack is here!");
}
But, I'm getting an error when try to run the same code inside a setTimeout function like below:
setTimeout(function(){
var someValue = $("[name='Jack']");
if(someValue !== null){
console.log("Jack is here!");
}
}, 1000);
Uncaught ReferenceError: $ is not defined
Not only does this happen in setTimeout function, it happens in a normal function as well.
I'm working with latest version of Google Chrome. How can I use JQuery like above in a setTimeout function?
The confusion here is centered on the fact that $ is part of Chrome's Command Line API. When you use $ in your code, you're referring to the Command Line API function named $. You are probably not loading jQuery at all: indeed, your someValue !== null code wouldn't even work with jQuery anyway. You'd need to test for a non-empty jQuery object (someValue.length > 0), not a non-null.
As for why Chrome's $ is accessible in the console but not a setTimeout callback: this appears to be engine-specific magic that limits the command line API to console code only. setTimeout executes its callback in such a way that Chrome cannot be sure the code originated from the console, so it does not grant access to the command line API function named $. Curiously, this isn't typical of JavaScript. Using normal JavaScript scoping rules, the setTimeout callback should have access to the same variables as the surrounding code, regardless of when and where it's executed. The fact that the scope is different one second later is very surprising -- you are right to feel confused!
As a curiosity, a way to simulate this in vanilla JavaScript would be with an object-based scope via with that mutates after the command completes. For example, if every snippet you typed into the console were wrapped with:
var chromeConsoleAPI = { $: function() { ... } }
with(chromeConsoleAPI) {
// your snippet here
}
delete chromeConsoleAPI.$;
In this case, $ is supplied by accessing the chromeConsoleAPI object on the scope chain. Normal code can access $, but since the setTimeout function runs after chromeConsoleAPI.$ is deleted, it does not find anything named $. Note that this still doesn't completely replicate the behavior, because this blocks access to any user-defined $. In actuality, the command line API must inject its functions at the very top (i.e., most remote) part of the scope chain.
The problem because Jquery library Load after your custome code loaded.
Are you using external js file for your custome script?
Then you load your script under the jquery script.
You must add jquery library link first then add your script.

Using the call function with setTimeout in Javascript results in an illusive error

I am working on a project in which a huge task is broken down using timeouts. The function being called uses the this keyword, so I'd like to do something like this:
setTimeout(myObj.myFunction.call, 1000, myObj);
But this results in a super-strange unexpected error at line 1 of the webpage (making it very difficult for me to pin-point what was causing the error when it happened):
Uncaught TypeError: object is not a function
The error doesn't even get caught by a try/catch. Try it in a jsfiddle.
Why does this happen? Is this my bug or a problem with Javascript? And is there a way to get my desired functionality short of passing in the scope object as a parameter to the called function?
Try setTimeout(function() {myObj.myFunction();}, 1000);
Using an anonymous function makes it much more explicit what you're trying to do, and it should work better for it.

Calling a method within a Javascript Object

I'm trying to create a javascript object that can call other methods within itself. However, I'm running into a weird problem that I just can't seem to figure out.
I have the following code
myObjectDef = function() {
this.init = function() {
//do some stuff
this.doSecondInit();
}
this.doSecondInit = function() {
//do some more stuff
}
}
myObject = new myObjectDef();
myObject.init();
I am getting an error that states "Message: Object doesn't support this property or method". And it ends at this.doSecondInit();. I can't quite figure out why it's doing this. My code runs great up to the call to the second method. How do I make this work?
There's an extra set of parenthesis here:
this.doSecondInit() = function() {
You can't assign to the result of a function call, let alone to the result of a function that doesn't even exist.
After your edit, your thing seems to work fine:
http://jsfiddle.net/nabVN/
You sure you didn't have the same typo in your actual code? Better start getting used to not putting that () after every function call, which is probably a bad habit carried over from languages where functions aren't values.

Unattached anonymous functions and doubly named methods in javascript?

I'm debugging an app that uses .NET's scriptmanager.
It may be a glitch in firebug, but when I read through the code there are a lot of lines like the following:
// anonymous functions not attached as handlers and not called immediately
function () {
//code
}
// named functions added as methods
myObj = {
myMethod: function myFunctionName() {
//code
}
}
Are these lines valid and, if so, what do they do and what possible reason would there be for coding like this (and I won't accept "It's microsoft - what d'you expect" as an answer)?
This might be worth a read: How does an anonymous function in JavaScript work?
They are there because some busy programmer was intending to do something and ran out of time, but left the stub as a reminder of work to be done. They do nothing as of yet.
or to watermark the code for checks that are done elsewhere in the logic
or simply put there to obfuscate...

Strange behavior on function calling

When calling a Javascript function, it seems like JS gives priority to functions without parameters first, even if I have the same function name with parameters.
The strange behavior only happens in the following scenario:
I have a an HTML page with embedded Javascript, like this:
//Javascript in the page
function testAbc(){
alert('testAbc no params');
}
//Javascript in common.js
function testAbc(x){
alert('testAbc with param:'+x);
}
function testAbcFunc(x){
testAbc(x);
}
Now from somewhere in the page, im calling testAbcFunc from the common.js expecting it to call testAbc with parameter which is the common function. But strangely, JS calls back the function in the original page without params!!
I have been debugging this bug fore few hours now, and i tried this short code to reproduce the bug, it does happen each time.
NOTE: if all functions are in the same page, the correct function (with params) will be called, but when ther are split between the page and the JS file. JS seems to give priority to the function in the page even though is doesn't have parameter
JavaScript does not support method overloading based on parameters. It simply uses the last-defined function if multiple functions have the same name. The version in the page will override the included version. When it worked for you, I assume that the include version (with the argument signature) was inlined after the original.
JavaScript doesn't have overloaded function. It doesn't care about signatures, it calls functions solely by names and nothing else. It is strange that later function does not completely hide the first one but well, there's no spec about that behaviour.
So just don't do that, check the number of params with arguments.length inside the function and don't try to use overloading which will never work.
function testAbc(){
if (arguments.length == 0) {
alert('testAbc no params');
} else {
var x = arguments[0];
alert('testAbc with param:'+x);
}
}
There is no function overloading in JavaScript. If you are defining a function with two times with diffrent number of parameters the last one to be defined will be called.
Also, you should be namespacing your JavaScript.
Like so:
var common = {
testABC: function () {
//Stuff
}
};
Then call testABC like this
common.testABC();

Categories