RequireJS - required items always return undefined - requirejs

I have never used RequireJS before, so any help would be appreciated.
I have the following HTML:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript"
data-main="CustomScripts/market-need"
src="CustomScripts/require.js"></script>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
</head>
<body>
etc...
</body>
</html>
I have the following JavaScript defined in CustomScripts/market-need.js.
(function(){
requirejs.config({ baseUrl: 'CustomScripts' });
require(['mndataservice'],
function (mndataservice) {
mndataservice.getListData();
});
})();
And the following code saved in CustomScripts/mndataservice.js.
define([], function () {
function getListData() {
alert("Hit");
}
return
{
getListData: getListData
};
});
Whenever I run the above, mndataservice is undefined when it hits the mndataservice.getListData(); line in the market-need.js. This worked at one point, I and I cannot find the error I have made for the life of me.

If you change:
function (mndataservice) {
mndataservice.getListData();
});
to:
function (mndataservice) {
this.mndataservice.getListData();
});
and then also replace the contents of mndataservice.js with:
var mndataservice = {
getListData: function () {
alert("Hit");
}
};
I think it will fix it for you.
Update:
Simply changing mndataservice.js to:
define([], function () {
return {
getListData: function () {
alert("Hit");
}
}
});
should fix it. Do not add "this." in the other function.
Update
Following up on your question below that asked why your example didn't work and mine did. The reason yours didn't work - your code is actually doing this:
define([], function () {
function getListData() {
alert("Hit");
}
return;
{
getListData: getListData
};
});
Note the semicolon right after the return keyword. Though not in your code, it gets inserted automatically by Javascript's Automatic Semicolon Insertion which causes it to return undefined rather than the object.
Moving the open curly brace up to same line as return fixes it!

Related

D3 in vscode webviews, can't see anything

I am trying to do a hello world example with d3 just to see if I can use the library. To this effect I copied this ultraminimialistic example into vscodes webview example.
This gave me the following code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const vscode = require("vscode");
const d3 = require("d3");
function activate(context) {
// Create and show a new webview
const panel = vscode.window.createWebviewPanel('catCoding', // Identifies the type of the webview. Used internally
'Cat Coding', // Title of the panel displayed to the user
vscode.ViewColumn.One, // Editor column to show the new webview panel in.
{} // Webview options. More on these later.
);
panel.webview.html = getWebviewContent();
d3.select(panel.document).append("span").text("Hello, world!");
context.subscriptions.push(vscode.commands.registerCommand('catCoding.start', () => {
}));
}
exports.activate = activate;
function getWebviewContent() {
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cat Coding</title>
</head>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
d3.select("body").append("span")
.text("Hello, world!");
</script>
</body>
</html>`;
}
// this method is called when your extension is deactivated
function deactivate() { }
exports.deactivate = deactivate;
//# sourceMappingURL=extension.js.map
My expectation was to see a hello world just like int he example, but I see this instead:
There are no alert messages, the problems, output and debug consoles are all fine and even the chrome dev console reports no errors. I am stuck.
There's 2 different attempts at using d3 in here, they both fail, one uses JS directly, the other uses HTML.

Require JS not working properly

I have made a simple code using require js. but output of another.js file is not coming to DOM.
this is my index.html.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Require JS app</title>
<script data-main="js/main" src="js/require.js"></script>
</head>
<body>
<div id="myapp"></div>
</body>
</html>
This is main.js file
require.config({
baseUrl: 'js/lib',
paths: {
"app": "../apps"
}
});
require(['jquery','app/another'], function($,message3) {
$('#myapp').html(message3);
})
This is another.js file
require (['jquery','app/anotherfile'], function($,message3) {
var message4="hello this is another file"+" "+message3;
return(message4);
});
and this is anotherfile.js
define(function(){
var message2="hello world";
return(message2);
})
In another.js file replace
require (['jquery','app/anotherfile'], function($,message3) {
var message4="hello this is another file"+" "+message3;
return(message4);
});
with
define (['jquery','app/anotherfile'], function($,message3) {
var message4="hello this is another file"+" "+message3;
return(message4);
});
and it will work

React, can't get past no method 'mountComponentIntoNode'

I have a html that looks like this:
<head>
<script src="../js/vendor/jquery-2.1.0.js"></script>
<script src="../js/vendor/react.js"></script>
<script src="../js/jsx/todo.js"></script>
</head>
<body>
<div id="ola"></div>
<script src="../js/popup.js"></script>
</body>
My todo.js is the compiled version TODO app from http://facebook.github.io/react/ minus the last line.
My last popup.js is:
$(function() {
React.renderComponent(TodoApp, document.getElementById('ola'));
})
But the page shows nothing! The console shows an error:
Uncaught TypeError: Object function (props, children) {
var instance = new Constructor();
instance.construct.apply(instance, arguments);
return instance;
} has no method 'mountComponentIntoNode' react.js:10052
I really don't know why is that, I've just tried to recreate from the example in the website. If it matters, it is in a chrome extension.
Ahhh got one line wrong on render!
popup.js should be:
React.renderComponent(TodoApp(), document.getElementById('ola'));

Does Jasmine 2.0 really not work with require.js?

I'm setting up my SpecRunner.html/.js, RequireConfig.js, my paths and my shims just like I have with earlier release candidates of Jasmine + RequireJs, but now my test methods show Jasmine undefined. They've recently changed to a different method of loading Jasmine that I understand is incompatible with RequireJs.
Is my understanding correct? If so, will we ever be able to use Jasmine + RequireJs again?
The new boot.js does a bunch of the initialization and attaches it to window.onload() which has already been called by the time require.js loads Jasmine. You can manually call window.onload() to initialize the HTML Reporter and execute the environment.
SpecRunner.html
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Jasmine Spec Runner v2.0.0</title>
<link rel="shortcut icon" type="image/png" href="lib/jasmine-2.0.0/jasmine_favicon.png">
<link rel="stylesheet" type="text/css" href="lib/jasmine-2.0.0/jasmine.css">
<!-- specRunner.js runs all of the tests -->
<script data-main="specRunner" src="../bower_components/requirejs/require.js"></script>
</head>
<body>
</body>
</html>
specRunner.js
(function() {
'use strict';
// Configure RequireJS to shim Jasmine
require.config({
baseUrl: '..',
paths: {
'jasmine': 'tests/lib/jasmine-2.0.0/jasmine',
'jasmine-html': 'tests/lib/jasmine-2.0.0/jasmine-html',
'boot': 'tests/lib/jasmine-2.0.0/boot'
},
shim: {
'jasmine': {
exports: 'window.jasmineRequire'
},
'jasmine-html': {
deps: ['jasmine'],
exports: 'window.jasmineRequire'
},
'boot': {
deps: ['jasmine', 'jasmine-html'],
exports: 'window.jasmineRequire'
}
}
});
// Define all of your specs here. These are RequireJS modules.
var specs = [
'tests/spec/routerSpec'
];
// Load Jasmine - This will still create all of the normal Jasmine browser globals unless `boot.js` is re-written to use the
// AMD or UMD specs. `boot.js` will do a bunch of configuration and attach it's initializers to `window.onload()`. Because
// we are using RequireJS `window.onload()` has already been triggered so we have to manually call it again. This will
// initialize the HTML Reporter and execute the environment.
require(['boot'], function () {
// Load the specs
require(specs, function () {
// Initialize the HTML Reporter and execute the environment (setup by `boot.js`)
window.onload();
});
});
})();
Example spec
define(['router'], function(router) {
'use strict';
describe('router', function() {
it('should have routes defined', function() {
router.config({});
expect(router.routes).toBeTruthy();
});
});
});
Here's an alternative approach that may be simpler in some cases - use Jasmine's asynchronous support to load your AMD module before executing tests, like this:
in MySpec.js:
describe('A suite', function() {
var myModule;
// Use require.js to fetch the module
it("should load the AMD module", function(done) {
require(['myModule'], function (loadedModule) {
myModule = loadedModule;
done();
});
});
//run tests that use the myModule object
it("can access the AMD module", function() {
expect(myModule.speak()).toBe("hello");
});
});
For this to work, you'll need to include require.js in your SpecRunner.html and possibly configure require (as you normally would, e.g. by setting the baseUrl), like this:
in SpecRunner.html:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Jasmine Spec Runner v2.0.0</title>
<link rel="shortcut icon" type="image/png" href="lib/jasmine-2.0.0/jasmine_favicon.png">
<link rel="stylesheet" type="text/css" href="lib/jasmine-2.0.0/jasmine.css">
<script src="lib/require.min.js"></script>
<script> require.config({ baseUrl: "src" }); </script>
<script src="lib/jasmine-2.0.0/jasmine.js"></script>
<script src="lib/jasmine-2.0.0/jasmine-html.js"></script>
<script src="lib/jasmine-2.0.0/boot.js"></script>
<script src="spec/MySpec.js"></script>
</head>
<body>
</body>
</html>
For this example, the AMD module implementation might look something like this:
in src/myModule.js:
define([], function () {
return {
speak: function () {
return "hello";
}
};
});
Here's a working Plunk that implements this complete example.
Enjoy!

Updating cache "bust" variable programatically in require.js

I am trying to update the bust variable in require.js so the browser is forced to re-fetch instead of loading resources from cache. I found here that several people have asked similar question. I am trying to try with a simple piece of code.
<html>
<head>
<title>jQuery+RequireJS Sample Page</title>
<!-- This is a special version of jQuery with RequireJS built-in -->
<script>
var require = {
urlArgs : "bust="+getRandom()
};
</script>
<script data-main="scripts/main" src="scripts/require-jquery.js"></script>
<script>
function getRandom() {
var buildNumber;
$.get("/resource/buildNumber", function(data) {
buildNumber = data;
});
return buildNumber;
}
</script>
</head>
<body>
<h1 id="heading">jQuery+RequireJS Sample Page</h1>
<p>Look at source or inspect the DOM to see how it works.</p>
</body>
I am trying to get the value of my build number from a properties file on the server. But I get the following error:
Uncaught ReferenceError: getRandom is not defined
So I tried this:
<script data-main="scripts/main" src="scripts/require-jquery.js"></script>
<script>
var require = {
urlArgs : "bust="+getRandom()
};
function getRandom() {
var buildNumber;
$.get("/resource/buildNumber", function(data) {
buildNumber = data;
});
return buildNumber;
}
</script>
But I get this error:
Uncaught TypeError: Property 'require' of object [object Object] is not a function
It looks like the bust variable has to be set even before require-jquery.js is declared but how do I access server side APIs without access to jquery libraries? I want to update the bust variable for every build.
Any pointers in the right directions would be really appreciated.
Thanks.

Resources