getting cocos2d-html5 to work with visual studio - javascript

<rant> I swear dealing with IDE problems are the worse. Its like all I want to do is get my hands dirty with some code but can't. </rant>
As the title suggest I am trying to get Cocos2d-HTML5 working in Visual Studio 2012. I have coppied the Cocos2d-HTML5 files to my web directory and followed a few of the tutorials but am having a problem with jsloader.js.
Prior to the change below it was not finding the jsloader.js :
FROM: `engineDir: '../cocos2d/',`
TO: `engineDir: '../GridWars/cocos2d/'`
Gridwars is the name of the project
Now it finds jsloader.js but has an error.
Unhandled exception at line 117, column 5 in http://localhost:51244/GridWars/cocos2d/platform/jsloader.js
0x800a138f - JavaScript runtime error: Unable to get property 'loadExtension' of undefined or null reference
for these lines of code:
var d = document;
var c = d.ccConfig;
if (c.loadExtension != null && c.loadExtension == true) {

Which version of Cocos2d-html5 did you used?
It is required to configure your settings in the cocos2d.js file. You may find this file in the template folder.
For example:
var c = {
COCOS2D_DEBUG:2, //0 to turn debug off, 1 for basic debug, and 2 for full debug
box2d:false,
chipmunk:false,
showFPS:true,
loadExtension:false, //**Hey, here is the loadExtension.....**
frameRate:60,
tag:'gameCanvas', //the dom element to run cocos2d on
engineDir:'../cocos2d/',
//SingleEngineFile:'',
appFiles:[
'src/resource.js',
'src/myApp.js'//add your own files in order here
]
};

v2.2 has a similar error. I found that moving a line around in your cocos2d.js file helps.
window.addEventListener('DOMContentLoaded', function () {
...
d.body.appendChild(s);
document.ccConfig = c;
s.id = 'cocos2d-html5';
//else if single file specified, load singlefile
});
Remove the line: document.ccConfig = c; and move it before the window.addEventListener
eg:
document.ccConfig = c;
window.addEventListener('DOMContentLoaded', function () {
// etc
});

The answer was posted on their release notes. I was following one of their tutorials and ended up finding my answer at the bottom of the post.
ANSWER:
in cocos2d.js
look for "s.c = c",
change it to "document.ccConfig = c"
in main.js
look for "config:document.querySelector('#cocos2d-html5')['c'],"
change it to "config:document.ccConfig,"

Related

Insert break point into a javascript file

I would like to insert break point at a position listed in the below quote. Let's say the below quote belongs to a js file called "test.js". What I would like to do is when I run "node test.js" on the command line, it will break at the break point and then I can inspect all the variables available at the break point.
var a = 4;
function changeA(input) {
var input = 6
[INSERT BREAK POINT HERE]
console.log(input)
};
changeA(a);
console.log(a);
Or is there another way to insert break point to a javascript file?
What you're looking for is the statement debugger;. You can insert that wherever you want, and if you run node debug test.js node will break wherever you placed the debugger; line.
Some of the basic commands once in debugging mode are:
c: continue
n: step next
s: step in
You also have the ability to set breakpoints manually once in debug mode, through the following command: setBreakpoint(line).
Hope this helps!
Resource: NodeJS Debugger API
You can hardcode a breakpoint like this:
debugger;
E.g.:
function changeA(input) {
var input = 6
debugger;
console.log(input)
}
...but you have to be using a debugger for it to mean anything, such as node-inspector. And if you're using a debugger, you can set breakpoints through the debugger itself (rather than hardcoding them).
Here's an example of debugging a very simple NodeJS script via node-inspector:
Script:
var a = +process.argv[2];
var b = +process.argv[3];
var c = a + b;
console.log("c = " + c);
Command to start node-inspector and pass my script a couple of args:
node-debug temp.js 10 20
A browser pops up with a debugging UI and the program paused. I've set a breakpoint through the UI on the var b = ... line, and then stepped passed it once, so I'm sitting on the var c = a + b; line (which hasn't run yet):
If built-in debugger is not something you want to use, you can try Node Inspector which allows you to debug your app using a nice GUI debug interface inside of a browser.

Show Javascript function filename programmatically

I need to know if there is a way to extract the script name when calling a variable or a function in javascript. The scenario is running chrome through webdriver or node and when calling for example window.jQuery.Animation I would like to get the filename (i.e., jquery.js) where this function is defined. I know in chrome you can click on 'show function code' and jump to the file, however I am looking to do the same in a programmatic way.
Thanks
Maybe an Error object can help here:
var e = new Error;
console.log(e.stack);
The first two lines of the stack:
Error
at Object.<anonymous> (/home/joost/src/test/testfile.js:3:9)
You have no such way of doing that in pure JavaScript.
The different javascript engines (spiderMonkey, V8, ...) will often compile the javascript code in some way, so you will lose such information in the process.
To know where a function comes from, you will require this function's source map. If you don't know them, source maps will map a script to it's originating filename / line number.
The mozilla sourceMap library will help you with that.
Though, you will have to generate a source map for your file that uses jQuery as well.
if your script.js is like
var a = jQuery.method // this is line 10
^ col 9
You will have to execute
var sourceMap = require('source-map');
consumer = new SourceMapConsumer('script.map');
consumer.originalPositionFor({ line: 10, column: 9 })
// { source: 'jQuery.js',
// line: 12971,
// column: 222,
// name: 'whatever' }
You'll be then able to query the original position and filename where that object is declared.

An object disappears after packing a JavaScript library

I have created a JavaScript library and packed it with these options selected : Shrink Variables and Base62 Encoded at this url: http://dean.edwards.name/packer/. In this library I have declared an object ax, but when I use the packed version in my web page I get an error saying Uncaught ReferenceError: ax is not defined.
The original code of this library looks like below.
var ax = {
scaleUp:function(win) {
//code omitted
},
downGrade:function(win) {
//code omitted
}
}
In my web page in which I am using this library, I have code like below. This code works, if instead of packing, I minify it using Microsoft's Minifier or just use the original JavaScript library without minification or packing.
var result = ax.downGrade(w);
Question :
Why is the variable ax not accessible with packed version? Do I need to add something else when using the packed version?
UPDATE 1:
I could not get the packed file to work but packing my code through another compression utility at following url worked in my case: http://jsutility.pjoneil.net/. It provided an equally good compression.
I am still not sure why the utility at original url failed to produce a working version of my library, even though my original code works without any errors on any web page.
Check your console for errors before trying to call ax. Explicitly place semi-colons where they belong.Example at the end of the definition for ax you should put a semi-colon, even though in standard code it's good as is. Remove the explicit var declarations. When I did these things:
ax = {
scaleUp:function(win) {
alert("up");
},
downGrade:function(win) {
alert("down");
}
};
result = ax.downGrade();
Ran without issue in jsFiddle and console: http://jsfiddle.net/7kdnw65n/. I suspect it has to do with how the algorithm "shrinks" the variables. The resulting pack was:
eval(function(p,a,c,k,e,r){e=String;if(!''.replace(/^/,String)){while(c--)r[c]=k[c]||c;k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('0={5:1(2){3("6")},4:1(2){3("7")}};8=0.4();',9,9,'ax|function|a|alert|downGrade|scaleUp|up|down|result'.split('|'),0,{}))

Auto-load/include for JavaScript

I have file called common.js and it's included in each page of my site using <script />.
It will grow fast as my sites functionality will grow (I hope; I imagine). :)
Lets example I have a jQuery event:
$('#that').click(function() {
one_of_many_functions($(this));
}
For the moment, I have that one_of_many_functions() in common.js.
Is it somehow possible that JavaScript automatically loads file one_of_many_functions.js when such function is called, but it doesn't exist? Like auto-loader. :)
The second option I see is to do something like:
$('#that').click(function() {
include('one_of_many_functions');
one_of_many_functions($(this));
}
That not so automatically, but still - includes wanted file.
Is any of this possible? Thanks in an advice! :)
It is not possible to directly auto-load external javascripts on demand. It is, however, possible to implement a dynamic inclusion mechanism similar to the second route you mentioned.
There are some challenges though. When you "include" a new external script, you aren't going to be able to immediately use the included functionality, you'll have to wait until the script loads. This means that you'll have to fragment your code somewhat, which means that you'll have to make some decisions about what should just be included in the core vs. what can be included on demand.
You'll need to set up a central object that keeps track of which assets are already loaded. Here's a quick mockup of that:
var assets = {
assets: {},
include: function (asset_name, callback) {
if (typeof callback != 'function')
callback = function () { return false; };
if (typeof this.assets[asset_name] != 'undefined' )
return callback();
var html_doc = document.getElementsByTagName('head')[0];
var st = document.createElement('script');
st.setAttribute('language', 'javascript');
st.setAttribute('type', 'text/javascript');
st.setAttribute('src', asset_name);
st.onload = function () { assets._script_loaded(asset_name, callback); };
html_doc.appendChild(st);
},
_script_loaded: function (asset_name, callback) {
this.assets[asset_name] = true;
callback();
}
};
assets.inlude('myfile.js', function () {
/* do stuff that depends on myfile.js */
});
Sure it's possible -- but this can become painful to manage. In order to implement something like this, you're going to have to maintain an index of functions and their corresponding source file. As your project grows, this can be troublesome for a few reasons -- the 2 that stick out in my mind are:
A) You have the added responsibility of maintaining your index object/lookup mechanism so that your scripts know where to look when the function you're calling cannot be found.
B) This is one more thing that can go wrong when debugging your growing project.
I'm sure that someone else will mention this by the time I'm finished writing this, but your time would probably be better spent figuring out how to combine all of your code into a single .js file. The benefits to doing so are well-documented.
I have created something close to that a year ago. In fact, I have found this thread by search if that is something new on the field. You can see what I have created here: https://github.com/thiagomata/CanvasBox/blob/master/src/main/New.js
My project are, almost 100% OOP. So, I used this fact to focus my solution. I create this "Class" with the name "New" what is used to, first load and after instance the objects.
Here a example of someone using it:
var objSquare = New.Square(); // Square is loaded and after that instance is created
objSquare.x = objBox.width / 2;
objSquare.y = objBox.height / 2;
var objSomeExample = New.Stuff("some parameters can be sent too");
In this version I am not using some json with all js file position. The mapping is hardcore as you can see here:
New.prototype.arrMap = {
CanvasBox: "" + window.MAIN_PATH + "CanvasBox",
CanvasBoxBehavior: "" + window.MAIN_PATH + "CanvasBoxBehavior",
CanvasBoxButton: "" + window.MAIN_PATH + "CanvasBoxButton",
// (...)
};
But make this more automatic, using gulp or grunt is something what I am thinking to do, and it is not that hard.
This solution was created to be used into the project. So, the code may need some changes to be able to be used into any project. But may be a start.
Hope this helps.
As I said before, this still is a working progress. But I have created a more independent module what use gulp to keep it updated.
All the magic que be found in this links:
https://github.com/thiagomata/CanvasBox/blob/master/src/coffee/main/Instance.coffee
https://github.com/thiagomata/CanvasBox/blob/master/src/node/scripts.js
https://github.com/thiagomata/CanvasBox/blob/master/gulpfile.js
A special look should be in this lines of the Instance.coffee
###
# Create an instance of the object passing the argument
###
instaceObject = (->
ClassElement = (args) ->
window[args["0"]].apply this, args["1"]
->
ClassElement:: = (window[arguments["0"]])::
objElement = new ClassElement(arguments)
return objElement
)()
This lines allows me to initialize a instance of some object after load its file. As is used in the create method:
create:()->
#load()
return instaceObject(#packageName, arguments)

"namespace is undefined" problem when using jsTestDriver, Idea 9 and testing 3 test cases. Sometimes it just outright hangs

I just started using jsTestDriver and I really like it, but all of a sudden, I just started getting a very weird error and I'm not sure what the heck I did to create it. Actually, if I try and run a basic Greeter test, the same problem happens.
Here's an example of one of my javascript files/classes under test:
myapp = myapp || {};
myapp.Module = function() {
...
};
All of the classes follow this pattern.
My test classes generally look like this (I'll give a really simple one):
ModuleTest = TestCase("ModuleTest");
ModuleTest.prototype.testInit = function() {
var module = new myapp.Module(); // <---- it bombs here, on every test!
assertFalse(module.isStarted);
module.init();
assertTrue(module.isStarted);
};
It bombs when it gets to "new myapp.Module()". Here is the error message that is given about 30 times for all my tests:
myapp is not defined
/src/test/webapp/js/ModuleTest.js:4
Here is my configuration file:
server: http://localhost:9876
load:
- src/main/webapp/js/jquery/*.js
- src/main/webapp/js/*.js
- src/test/webapp/js/*.js
Does anyone have any idea what the heck is wrong? Sometimes when I run all the tests in IDEA, my IDE just hangs altogether or takes like many minutes for jsTestDriver to finally report the above results...
:(
I faced the same issue after I moved to v.1.3.1. In my case the problem was with file encoding. I use Visual Studio for the development, it adds byte order mark (3 extra bytes) in the beginning of the file. It's possible to see these bytes in Far manager. If you use VS try to save the file as the following: "File->Advanced save options->" Encoding: Unicode (UTF-8 without signature) - Codepage 65001.
It should fix your problem.

Categories

Resources