RequireJS main require call back never invoked - javascript

I've tried this post's advice to no avail. No matter what I do, RequireJS's primary callback is never fired. Here's my dependency graph:
/module/main.js
-- /module/mainController.js
--/vendor/preloadjs
--/module/itemController.js
--/module/router.js
--/vendor/crossroads.js
--/vendor/signals.js
--/vendor/hasher.js
--/vendor/signals.js
require.config({
baseUrl: "script/module",
paths: {
signals: "vendor/signals"
}
});
require(["main", function(){
console.log("main function!");
}]);
The "main" module makes use of js-signals, and actually gets invoked. In fact the entire dependency tree is loaded (confirmed via the web inspector). I have a single entry point for the application. All modules start up and actually run fine. You'd think that if the main application callback doesn't run that one or all of its dependencies would have failed.
I'm sure there is some stupid reason I'm not kicking off the primary require's callback. For the record I've tried using the requirejs() method and get the same results.
No files have code in them except for dependencies and console.logs.
Does anyone have any ideas for what I'm doing wrong?

I'll answer my own silliness. The problem is right there in the source. I'm using Angular module injection syntax, and passing the callback as part of the dependency array. Oops. It needs to be the second argument!
Long story short, the code is right, but this is the change:
require.config({
baseUrl: "script/module",
paths: {
signals: "vendor/signals"
}
});
require(["main"], function(){
console.log("main function!");
});

Related

How do I detect when Emscripten's generated .js finishes loading the wasm so I can run my JS functions which call it?

I'm using Emscripten to compile some C code to WebAssembly. This is the final emcc call in my Makefile:
emcc $(CFLAGS) iva.a -o iva.js
Which works as intended and generates a .js file and a .wasm file. The JS is loaded into my HTML page as follows:
<script src="../dist/iva.js">
And it loads and instantiates the WebAssembly code iva.wasm properly. This message appears in the console soon after I load the page:
Fetch finished loading: GET "http://localhost:6931/dist/iva.wasm".
Which I take to mean that my WebAssembly is loaded through a fetch() and, perhaps pending some processing, I can access my functions through the console:
Module._init_display_system()
And get the return values. This holds true and everything works.
Clearly, I should be able to do this through a script as well. However, I can't see a way to only run a function after my WebAssembly has been instantiated. I get the feeling that I'm missing something rather obvious.
Anyway, how do I do this?
Use Module['onRuntimeInitialized'].
Module['onRuntimeInitialized'] = function() {
console.log("wasm loaded ");
var x=Module.ccall("doubleIt","number",["number"],[20]);
alert(x);
}
You have used emsdk, there are online WASM compilers like Wasmfiddle. Find my github repo useful for both the methods.
While the two solutions of Sudhakar RS and Anil8753 are totally fine, I want to add, that you have to execute this approach before you load your WebAssembly. Otherwise it might be too late to catch the event.
Besides that, there is another approach, which uses promises. If you add
-s MODULARIZE=1 -s 'EXPORT_NAME="createMyModule"'
as options when compiling with emcc, your resulting .js will contain the function createMyModule. This function will return a Promise that resolves as soon as your WebAssembly code is ready to use. Example usage:
In your HTML, add your WebAssembly as you already did:
<script src="../dist/iva.js">
In your js, call the function and after the promise resolved, you are good to go:
createMyModule().then(MyModule => {
console.log('WebAssembly loaded!');
// Access your functions (if bound by Embind):
console.log(MyModule.getSomething());
});
<script>
var Module = {
onRuntimeInitialized: function() {
console.log('module loaded');
}
};
</script>

Gulp Watch Not calling associated gulp task

So I'm coming back to a personal project after a (prolonged) break, and I'm getting back into the flow of things. One thing that smacks me in the face is that my watchers aren't working. If, for example, I call gulp watch-for-jshint, I expect JSHint to be changed anytime I modify a JS file -- either a root one (gulp.js) or one of my client-app ones (./client-app/js/controllers/register.js). That's not happening. I can see watch is starting, but it never calls JSHint when I change my files!
Anyone have any ideas what is going wrong or how to diagnose? As far as I can tell, I have the syntax right... And because (for testing purposes) I'm directly calling watch-for-jshint, I should be avoiding the usual pitfall of never actually calling my watcher.
Simplified gulp file:
var gulp = require('gulp'),
clean = require('gulp-clean'),
jshint = require('gulp-jshint'),
notify = require('gulp-notify'),
watch = require('gulp-watch'),
gulp.task('jshint', function(){
console.log("Running JSHint");
return gulp.src(['*.js', 'client-app/**/*.js'], ['jshint'])
.pipe(jshint({"moz":true}))
.pipe(jshint.reporter('default'))
.pipe(jshint.reporter('fail'))
.on('error', notify.onError({ sound: "Funk" }));
});
gulp.task('watch-for-jshint', function(){
return watch(['*.js', './client-app/**/*.js'], ['jshint']);
});
I've truncated a lot of extraneous tasks, but what's above should be everything relevant.
And naturally, 5 minutes after posting I notice one difference between my syntax and what a lot of questions are using. Most people are using gulp.watch, I was just following the syntax found at the gulp-watch NPM module page of using just watch.
Not... entirely sure why one works and the other doesn't; odd. Seems like the new version shouldn't work, since it's not referencing the gulp-watch module.
Remove the following line in gulp task, if it is not necessary.
.on('error', notify.onError({ sound: "Funk" }))
This makes the gulp task stop and show error. Hence watch is also stopped.
Replace
return watch(['*.js', './client-app/**/*.js'], ['jshint']);
with
gulp.watch(['*.js', './client-app/**/*.js'], ['jshint']);

Custom Yeoman Generator can't overwrite files

I'm trying to create a simple generator to standardize creation of node projects. In my generator I make calls to copyTpl like:
generator.fs.copyTpl(
sourcePath,
destinationPath
context,
//ignore ES6 constructs in our templates
{
interpolate: /<%=([\s\S]+?)%>/g
}
);
This works great as long as no files exist in my target directory. Unfortunately, if a file exists and I choose to overwrite it I get the following error:
Error: no writecb in Transform class
at afterTransform (/Users/gerrard00/projects/generator-mine/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js:95:33)
at TransformState.afterTransform (/Users/gerrard00/projects/generator-mine/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js:79:12)
at Object.callback (/Users/gerrard00/projects/generator-mine/node_modules/yeoman-generator/lib/base.js:787:7)
at /Users/gerrard00/projects/generator-mine/node_modules/yeoman-generator/lib/util/conflicter.js:79:18
at Conflicter.<anonymous> (/Users/gerrard00/projects/generator-mine/node_modules/yeoman-generator/lib/util/conflicter.js:193:12)
at PromptUI.onCompletion (/usr/local/opt/nvm/versions/node/v5.0.0/lib/node_modules/yo/node_modules/inquirer/lib/ui/prompt.js:57:10)
at AnonymousObserver.Rx.AnonymousObserver.AnonymousObserver.completed (/usr/local/opt/nvm/versions/node/v5.0.0/lib/node_modules/yo/node_modules/rx-lite/rx.lite.js:1550:12)
at AnonymousObserver.Rx.internals.AbstractObserver.AbstractObserver.onCompleted (/usr/local/opt/nvm/versions/node/v5.0.0/lib/node_modules/yo/node_modules/rx-lite/rx.lite.js:1489:14)
at Subject.Rx.Subject.addProperties.onCompleted (/usr/local/opt/nvm/versions/node/v5.0.0/lib/node_modules/yo/node_modules/rx-lite/rx.lite.js:5871:19)
at Subject.tryCatcher (/usr/local/opt/nvm/versions/node/v5.0.0/lib/node_modules/yo/node_modules/rx-lite/rx.lite.js:63:31)
This means that my generator only works in empty folders. I've re-read the "Creating a generator" docs about twenty times, but I can't figure out what I'm missing. What do I need to add to my generator to prevent this error?
Update: The files are actually overwritten, despite the error.
It turns out that the issue was with the fact that my code was walking a directory asynchronously using the node-walk package. The calling method used the generator async method, but called the done callback synchronously. I modified it to call the done callback in the walk end event handler and the error went away.

Q.js and order of execution confusion within ASP.NET MVC

I have adopted the library Q.js into my program to try and solve some problems with the order of execution in my code, I am new to promises and deferred in general, so this is a pretty difficult step for me.
At this point in time, I am using Q v1 within ASP.NET MVC, and therefore I am using Visual Studio 2013.
Now, the actual code for what I am doing is a great deal longer than this, but I'll attempt to be concise, as I often get told my questions are too long and verbose.
I start by including q.js and require.js normally, nothing special is going on here. It works fine, it compiles, it runs, all is happy and well.
#Scripts.Render("~/scripts/q")
#Scripts.Render("~/scripts/require")
<script type="text/javascript">
Q().then(function(){
// some code executes here.
$.blockUI(); // the whole page is blocked while loading.
console.log("[1] first step. blocking the page.");
}).then(function() {
console.log("[2.1] starting the second step.");
require(['home/app/init'], function(app) {
console.log("[2.2] within the require function.");
new app.init().wiring(); // this does some preliminary stuff for the app
});
console.log("[2.3] outside of the require function.");
}).then(function() {
console.log("[3.1] made it to the third step. stuff happens.");
});
</script>
Now, running this code, the console output for 2.1 and 2.3 are visible before 2.2 - which is the crux of the problem. I want it to run in order. So I dug a bit more, and found this suggestion; changing my require call to look more like this was suggested to me ..
// ....
.then(function(){
var promise = Q.when(require['home/app/init'], function(app) {
console.log("[2.2.1] within the require");
new app.init().wiring();
}).then(function() {
console.log("[2.2.2] I expect to see this after 2.2.1");
});
console.log("[2.3] outside of the require function.");
});
Now I get that 2.3 will still run before 2.2.1, but I'm still seeing 2.2.2 running before 2.2.1 - and I thought that wrapping the behavior in the Q.when(fn) was supposed to fix that?
Can someone help me understand why these are not running in the order I am asking them to?
For a bit more information, the file home/app/init is actually a Typescript file that looks a bit like this;
home/app/init.ts
export class init {
public function wiring() {
// some simple things happening here, nothing special.
}
}
I am not sure if this question qualifies to have the ASP.NET MVC tag, but the fact that I am using that framework is paramount to the tooling I use, which does have influence over what I can do (for instance, I'm having a hard time with things involving node.js because of Visual Studio) - so I am tagging it explicitly to be sure people realize the kind of development environment I am in.
Update
I have made a bit of progress on this, though I am still a bit uncertain. At the moment, the following code seems to run more in the order I am expecting.
// .....
.then(function(){
console.log("[2.1]");
// create a deferred promise
var deferred = Q.defer();
require(['home/app/init'], function(app) {
// we are inside the require function
console.log("[2.2]");
// run the actual method
new app.init().wiring();
// report back to the console.
console.log("[2.3]");
// resolve the promise
deferred.resolve();
});
console.log("[2.4]");
Q.when(deferred.promise).then(function() {
console.log("[2.5]");
}).then(function(){
// ... continue
});
This at least seems to cause the code to pause and wait for the require to finish before it goes on to 2.5, but I'm not sure if this is the correct way to do this with Q.js.
2.1 will run before 2.2 because that's the order you are running the code but the 2.2 code runs asynchronously so gets run once require has got everything in order which will take more time than it takes the 2.3 code to execute
I think in your second block of code you want to move the 2.2.2 block inside the when see the documentation for when at the bottom of this page
https://github.com/kriskowal/q

how should I write my define to work with curl.js?

I'm reading Addy Osmani's excellent blog post about writing AMD modules. I start with a simple chunk of js that I lifted from his post:
define('modTest', [],
// module definition function
function () {
// return a value that defines the module export
// (i.e the functionality we want to expose for consumption)
// create your module here
var myModule = {
doStuff:function(){
console.log('Yay! Stuff');
}
}
return myModule;
}
);
I took out the dependencies on foo and bar. Just want a simple object that logs to the console.
So I save that in /js/modTest.js and then try to load it:
curl(['/js/modTest.js'])
.then(function(mt) {
console.log("Load complete");
console.log("mt:");
console.log(mt);
mt.doStuff()
}, function(ex) {alert(ex.message);})
Result: error: Multiple anonymous defines in URL. OK that didn't work. Tried adding in a namespace: define('myCompany/modTest', [],, same result. Tried adding an empty string in the dependency array, same result.
Also tried curl(['modTest.js'], function(dep){console.log(dep)}); with the same result.
Is the code in Addy's blog post incorrect? Am I doing something wrong? Maybe a bug in curl?
Update 5/24: I ditched curl.js in favor of require.js. Zero odd errors, very little work to change over. I did have to deal with amdefine a bit to get my code running client and server side (one object is in both places, so grunt had to be configured to take care of that). My defines generally look like:
define(->
class AlphaBravo
...
And never have any trouble loading.
You asked curl() to fetch a module called "/js/modTest.js". It found the file and loaded it and found a module named "modTest", so it complained. :) (That error message is horribly wrong, though!)
Here's how you can fix it (pick one):
1) Remove the ID from your define(). The ID is not recommended. It's typically only used by AMD build tools and when declaring modules inside test harnesses.
2) Refer to the module by the ID you gave it in the define(). (Again, the ID is not recommended in most cases.)
curl(['modTest'], doSomething);
3) Map a package (or a path) to the folder with your application's modules. It's not clear to me what that would be from your example since modTest appears to be a stand-alone module. However, if you were to decide to organize your app's files under an "app" package, you packages config might look like this:
packages: [ { name: 'app', location: 'app' } ]
Then, when you have code that relies on the modTest module, you can get to it via an ID of "app/modTest".
curl(['app/modTest'], doSomething);
I hope that helps clear things up!
Fwiw, Addy's example could actually work with the right configuration, but I don't see any configuration in that post (or my eyes missed it). Something like this might work:
packages: [ { name: 'app', location: '.' } ]
-- John
I've just had a similar problem which turned out to be the include order I was using for my other libraries. I'm loading handlebars.js, crossroads.js, jquery and a few other libraries into my project in the traditional way (script tags in head) and found that when I place the curl.js include first, I get this error, but when I include it last, I do not get this error.
My head tag now looks like this:
<script type="text/javascript" src="/js/lib/jquery.js"></script>
<script type="text/javascript" src="/js/lib/signals.js"></script>
<script type="text/javascript" src="/js/lib/crossroads.js"></script>
<script type="text/javascript" src="/js/lib/handlebars.js"></script>
<script type="text/javascript" src="/js/lib/curl.js"></script>
<script type="text/javascript" src="/js/main.js"></script>
You have a problem with your define call. It is NAMED
See AMD spec for full story on how to write defines, but here is what I would expect to see in your js/modTest.js file:
define(/* this is where the difference is */ function () {
// return a value that defines the module export
// (i.e the functionality we want to expose for consumption)
// create your module here
var myModule = {
doStuff:function(){
console.log('Yay! Stuff');
}
}
return myModule;
}
);
Now, the boring explanation:
CurlJS is awesome. In fact, after dealing with both, RequireJS and CurlJS, I would say CurlJS is awesome-er than RequireJS in one category - reliability of script execution ordering. So you are on the right track.
On of the major things that are different about CurlJS is that it uses "find at least one anonymous define per loaded module, else it's error" logic. RequireJS uses a timeout, where it effectively ignores cases where nothing was defined in a given file, but blows up on caught loading / parsing errors.
That difference is what is getting you here. CurlJS expects at least one anonymous (as in NOT-named) define per loaded module. It still handles named defines fine, as expected. The second you move the contents of "js/modTest.js" into inline code, you will have to "name" the define. But, that's another story.

Categories

Resources