Javascript function out of scope - require js - javascript

I have a JS file named ui.js and a function within it does something. This file looks something like this
define(function (require) {
function someName(param1, param2, param3) {
......
};
}
In another JS file, I call all of my JS files like so:
define(function (require) {
var $ = require('jquery');
var functionName = require('ui');
$(function() {
function one() {
.....
someName(value1, value2, value3);
}
});
});
function one works without mistake, but when i call function someName within it, then i get an error someFunction is not defined. I must be out of the scope, but I don't know how to get this working. I tried to console.log outside and inside the someName function, and I get the log from outside but not the log from inside. Any ideas?
///// EDIT
I just mistyped it here, I have the closing brackets in my code

I guess you're looking for this:
ui.js
define(function() {
return function(param1, param2, param3) {
...
};
}
someOtherModule.js
define(["jquery", "ui"], function($, ui) {
$(function() {
...
ui(v1, v2, v3);
});
});
If ui.js should propose several methods:
ui.js
define(function() {
return {
f1: function() {
...
},
f2: function() {
...
}
};
}
someOtherModule.js
define(["jquery", "ui"], function($, ui) {
$(function() {
...
ui.f1();
ui.f2();
});
});

Related

Typescript self executing function won't fire if there is an import

Consider this Typescript:
(()=> {
console.log('called boot'); // 'called boot'
})();
resulting JS:
(function () {
console.log('called boot');
})();
define("StockMarketService", ["require", "exports", "jquery"], function(require, exports, $) {
"use strict";
var StockMarketService = (function (_super) {
__extends(StockMarketService, _super);
...blah...
return StockMarketService;
}(Riot.Observable));
exports.StockMarketService = StockMarketService;
});
VS Typescript:
import {StockMarketService} from "./services/stockmarket-service";
(()=> {
console.log('called boot'); //NOTHING HAPPENS.
})();
Resulting JS:
define("StockMarketService", ["require", "exports", "jquery"], function(require, exports, $) {
"use strict";
var StockMarketService = (function (_super) {
__extends(StockMarketService, _super);
...blah...
return StockMarketService;
}(Riot.Observable));
exports.StockMarketService = StockMarketService;
});
define(["require", "exports"], function (require, exports) {
"use strict";
(function () {
console.log('called boot');
})();
});
In the second version the IFFE no longer works. This is the entry point to the application. It's not a module. I just want to execute the IFFE. All the dependencies are in the one file, and I need to reference/use them.
What am I doing wrong?
In the second version the IFFE no longer works.
The second example is module (more on this). Module bodies only execute if something requests the module. If you use the module (somewhere in the chain) from your application root the module body would execute. 🌹
any js code is valid TypeScript code,
so change
import {StockMarketService} from "./services/stockmarket-service";
(()=> {
console.log('called boot'); //NOTHING HAPPENS.
})();
to
import {StockMarketService} from "./services/stockmarket-service";
(function () {
console.log('called boot');
})();

Uncaught ReferenceError: ModuleA is not defined

I am using following code which uses prototypal inheritance. Somehow when I create a new instance of ModuleA then it return
Uncaught ReferenceError: ModuleA is not defined
Below is my code
(function () {
var ModuleA = function () {
console.log('ModuleA');
};
ModuleA.prototype = (function () {
var moduleA = function () {
};
return {
moduleA: moduleA
}
}());
return ModuleA;
})();
new ModuleA();
UPDATE
JSFIDDLE
It's because you explicitely put your ModuleA declaration in an IIFE which will hide everything inside. So ModuleA is in the scope of your IIFE. You did return return ModuleA but you didn't put it anywhere.
Do this instead :
var ModuleA = (function () {
var ModuleA = function () {
console.log('ModuleA');
};
ModuleA.prototype = (function () {
var moduleA = function () {
};
return {
moduleA: moduleA
}
}());
return ModuleA;
})();
new ModuleA();

How to programatically inject html to qunit-fixture

I would like to programatically inject the html to test into the qunit-fixture. I have tried with $.load but the JS dealing with the HTML gets executed before the html is loaded.
The HTML:
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<script src="../components/bower/qunit/qunit/qunit.js"></script>
<script>
QUnit.config.autostart = false;
</script>
<script data-main="tests" src="../components/bower/requirejs/require.js"></script>
The JS manipulating the html is the module I want to test:
define(['jquery'], function($) {
'use strict';
var Foo = {
_init: function() {
this._addClass();
},
_addClass: function() {
console.log('adding class testit');
$('.foo').addClass('testit');
},
greet: function() {
return "Hello";
}
};
Foo._init();
return {
greet : Foo.greet
};
});
And my test:
define(['foo'], function(foo) {
'use strict';
var Test = {
test: function() {
module( "module Foo");
asyncTest("foo class test", function() {
expect(1);
// foo() is executed before load is done :(
$('#qunit-fixture').load('../components/app/foo/foo.html', function(data) {
ok($('.foo').hasClass('testit'), ".foo should have class 'testit'");
QUnit.start();
});
});
}
};
return {
test: Test.test
};
});
Since the loading of the content is asynchronous you'll need to tell QUnit to wait before running. Note that this is just a guess at what your test harness might look like, it will likely need to be updated for your use case.
<!-- in your test HTML document -->
<script>
QUnit.config.autostart = false;
// your code to load the HTML dynamically in the fixture
// your test definitions
require(
[ "src/yourSourceCode", "tests/theTests" ],
function() {
QUnit.start(); // this starts the main QUnit code
}
);
</script>
UPDATE
Looks like the OP is, in fact, already stopping QUnit from running immediately, the problem (see the comment below) is that the module code runs before the HTML is loaded dynamically. I think this is because the _init() method is called inside the module. Instead, return the _init method as a property of the module and call it from the test:
define(['jquery'], function($) {
'use strict';
var Foo = {
_init: function() {
...
},
...
};
// Foo._init(); // don't do this here...
return {
greet : Foo.greet,
init : Foo._init // add the init method to your exports
};
});
Now, in your test you can do:
define(['foo'], function(foo) {
'use strict';
var Test = {
test: function() {
module( "module Foo");
asyncTest("foo class test", function() {
expect(1);
$('#qunit-fixture').load('../components/app/foo/foo.html', function(data) {
foo.init(); // we've moved the initialization to here...
ok($('.foo').hasClass('testit'), ".foo should have class 'testit'");
QUnit.start();
});
});
}
};
return {
test: Test.test
};
});

require js load function from a modul

despite i found already some answers i could not figure it out where i made the mistake in loading the module with require js, i always get the error Uncaught
TypeError: undefined is not a function
at the line where i try to call the function in the zoom.js file
myZoomingFunctions.minSize();
here my code:
main.js
require.config({
baseUrl: 'js/libs',
paths: {
'jquery': 'jquery-1.9.1',
'myDraw': '../draw',
'myZoomingFunctions': '../zoom'
}
});
require(['jquery', 'myDraw'], function ($, myDraw_ref) {
var myDraw = new myDraw_ref();
});
draw.js
define(['myZoomingFunctions'], function (myZoomingFunctions_ref) {
var myZoomingFunctions = new myZoomingFunctions_ref();
return draw = function() {
myZoomingFunctions.minSize();
}
});
zoom.js
define([], function () {
return zoom = function() {
function minSize(){
alert("minSize called");
}
}
});
thanks!
i figured out, maybe if someone else have the same problem, here is the solution:
main.js
require.config({
baseUrl: 'js/libs',
paths: {
'jquery': 'jquery-1.9.1',
'myDraw': '../draw',
'myZoomingFunctions': '../zoom'
}
});
require(['jquery', 'myDraw'], function ($, myDraw_ref) {
var myDraw = new myDraw_ref();
});
draw.js
define(['myZoomingFunctions'], function (myZoomingFunctions) {
return draw = function() {
myZoomingFunctions.minSize();
myZoomingFunctions.maxSize();
}
});
zoom.js
define([], function () {
return {
minSize: function() {
alert("min Size called");
},
maxSize: function() {
alert("max Size Called");
}
}
});

Why is `Mustache` undefined? (Using RequireJS)

I can see that the mustache.js file has been loaded, (code 200 in Firebug Net tab) so why do I get an error saying "ReferenceError: Mustache is not defined"?
I've looked at several related SO posts on this subject, but none seem to shed light on the issue. Any help is appreciated.
Relevant HTML
<div class="contact"></div>
<script data-main="js/modules/app.js" src="js/lib/require.min.js"></script>
app.js
var KBCOM = KBCOM || {};
(function (kbcom) {
kbcom.app = {
data: {
kboucher: "{ \"firstName\": \"Kevin\", \"lastName\": \"Boucher\", \"dob\": \"1970-05-01T05:00:00.000Z\", \"emailAddress\": \"example#mail.com\", \"telephone\": \"512-555-1212\" }"
},
init: function () {
kbcom.templates.loadTemplate(
kbcom.templates.vcard,
JSON.parse(this.data.kboucher),
document.querySelector('.contact'));
}
};
}(KBCOM));
require.config({
baseUrl: '/js/modules',
paths: {
Mustache: '/js/lib/mustache',
domReady: '/js/lib/domReady'
}
});
require(['domReady', 'templates', 'Mustache'], function (domReady) {
domReady(function () {
KBCOM.app.init();
});
});
templates.js
var KBCOM = KBCOM || {};
(function (kbcom) {
kbcom.templates = {
vcard: '<ul>\
<li class="fn">{{fisrtName}} {{lastName}}</li>\
<li class="email">{{emailAddress}}</li>\
<li class="tel">{{telephone}}</li>\
<li class="bday">{{dob}}</li>\
</ul>',
loadTemplate: function (template, data, element) {
element.innerHTML = Mustache.render(template, data);
}
};
}(KBCOM));
templates.js "requires" Mustache, therefore you need to define that dependency in templates.js. It also needs to be defined as a module, so you need to use define to properly create a module.
app.js
require(['domReady', 'templates'], function (domReady, templates) {
//append templates to namespace
KBCOM.templates = templates;
domReady(function () {
KBCOM.app.init();
});
});
templates.js
define([
//dependencies
'Mustache'
], function( Mustache ){
//module code
return {
vcard: '...',
loadTemplate: function ( template, data, element ) {
element.innerHTML = Mustache.render( template, data );
}
};
});
Require will bind the variables of the libraries to the parameters of the function given in the second parameter, so to use templates and Mustache in your code you should do the following:
require( [ 'domReady', 'templates', 'Mustache' ],
function( domReady, templates, Mustache ) {
domReady( function () {
KBCOM.app.init();
} );
}
);

Categories