Reputation: 1861
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.
Upvotes: 0
Views: 3065
Reputation: 121
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!
Upvotes: 1