First question here and it is 3:30AM so please bear with me as I try to explain my question.
I'm in the situation that I need a very big javascript object. Good practice learns me that I shouldn't expose anything to the window object unless absolutely necessary.
This object I made requires some sort of customization (settings) and an object containing different kind of customization (levels). The first object is not that big, but the second one is becoming quite big and will grow bigger in the future.
I figured it would be nice to split these objects into different files and want to use browserify for it. I dont however want the two objects available within the window scope.
// settings.js
var settings = {
"setting1": "hellp",
"setting2": "world"
}
module.exports = settings;
//levels.js
var levels = {
"level1": {
name: "level1",
type: "flat",
},
"level2": {
name: "level2",
type: "hills"
} //about 10 more...
}
module.exports = levels;
//world.js
var world = function() {
var self = this;
var settings = require('settings.js');
var levels = require('levels.js');
self.test = function() {
console.log(settings['setting1'] + " " + settings['setting2']; console.log(levels['level1'].name);
}
return self;
}
I work with browserify and gulp to append this into one /dist/world.js but in a test html page it always shows "world is undefined", while it does work when I append the file myself.
I figured I did something wrong with browserify but the gulp task I use for it works on other projects:
function handleError(level, error) {
gutil.log(error.message);
process.exit(1);
}
// Convenience handler for error-level errors.
function onError(error) {
handleError.call(this, 'error', error);
}
gulp.task('browserify', function () {
var b = browserify({
entries: './main.js',
paths: ['./www-src'],
debug: true
});
return b.transform(p)
.bundle()
.on('error', onError)
.pipe(source('main.js'))
.pipe(buffer())
.pipe(gulp.dest('./dist/'));
});
basically what im calling is this in the index.html:
//index.html
var world = new world();
world.test()
and it throws the "world is undefined" error
Is anyone able to give me any pointers how to fix this issue? Would really appreciate any help!
update:
I know that IFFE means immediately invoked function expression, in other words a function that gets executed immediately. What I dont get is how to access this.
Related
I jumped into the deep end recently and have been slowly learning to swim. I'm working on a CLI for building out a simple text game world. That code is becoming a convoluted mess and so I have tried to recreate the error I am getting in a simpler form below.
Try as I might I can't seem to understand the best way to structure all of my functions. In my project I have a parser function that breaks input up and searches for a 'verb' to invoke via a try/catch block. When a verb i.e. 'look' runs it accesses my database module and sends a query based on several parameters to return the description of a room or thing. Because this is all asynchronous virtually everything is wrapped in a promise but I am leaving that out of this example. The following is not the actual project, just a simple recreation of the way I have my objects set up.
APP:
// ***********************
const player = require('./scope_test_player');
player.look();
player.water();
Module1:
// ***********************
const apple_tree = require('./scope_test_apple_tree');
module.exports = {
look: function(){
console.log(
'The apple tree is '+apple_tree.height+'ft tall and has '
+apple_tree.apples+' apples growing on it'
);
},
water: function() {
apple_tree.grow();
}
};
Module2:
// ***********************
const player = require('./scope_test_player');
module.exports = {
height: 10,
nutrition: 0.3,
apples: [],
fertilize: function(number) {
this.nutrition+=number;
},
grow: function() {
this.height+=this.nutrition;
}
};
In the above code I get 'TypeError: apple_tree.grow is not a function' from water or undefined from look. This is the bane of my existence and I have been getting this seemingly at random in my main project which leads me to believe I dont understand scope. I know I can require the module within the function and it will work, but that is hideous and would add hundreds of lines of code by the end. How do I cleanly access the functions of objects from within other objects?
You problem is that have a cyclic dependencies in your project and that you overwrite the exports property of the module. Because of that and the way node cachges required modules, you will get the original module.exports object in scope_test_player file and not the one you have overwritten. To solve that you need to write it that way:
// ***********************
const apple_tree = require('./scope_test_apple_tree');
module.exports.look = function() {
console.log(
'The apple tree is ' + apple_tree.height + 'ft tall and has ' + apple_tree.apples + ' apples growing on it'
);
};
module.exports.water = function() {
apple_tree.grow();
};
And
// ***********************
const player = require('./scope_test_player');
module.exports.height = 10;
module.exports.nutrition = 10;
module.exports.apples = [];
module.exports.fertilize = function(number) {
this.nutrition = +number;
};
module.exports.growth = function() {
this.height = +this.nutrition;
}
But this is a really bad design in gerenal and you should find another way how to solve that. You should always avoid loops/circles in your dependency tree.
UPDATE
In node each file is wrappted into load function in this way:
function moduleLoaderFunction( module, exports /* some other paramteres that are not relavant here*/)
{
// the original code of your file
}
node.js internally does something like this for a require:
var loadedModules = {}
function require(moduleOrFile) {
var resolvedPath = getResolvedPath(moduleOrFile)
if( !loadedModules[resolvedPath] ) {
// if the file was not loaded already create and antry in the loaded modules object
loadedModules[resolvedPath] = {
exports : {}
}
// call the laoded function with the initial values
moduleLoaderFunction(loadedModules[resolvedPath], loadedModules[resolvedPath].exports)
}
return loadedModules[resolvedPath].exports
}
Because of the cyclic require, the require function will return the original cache[resolvedPath].exports, the one that was initially set before you assinged your own object to it.
Is Module1 = scope_test_player and Module2 = scope_test_apple_tree?
Maybe you have a cyclic reference here?
APP requires scope_test_player
// loop
scope_test_player requires scope_test_apple_tree
scope_test_apple_tree requires scope_test_player
// loop
As I can see scope_test_apple_tree doesn't use player.
Can you try to remove:
const player = require('./scope_test_player');
from Module2 ?
There are a few issues to address.
Remove the player require in Module 2(scope_test_apple_tree.js):
const player = require('./scope_test_player')
It doesn't do any damage keeping it there but it's just unnecessary.
Also, replace =+ with += in fertilize and grow which is what I think you are going for.
I was able to run the code natually with those fixes.
If you want to refactor, I'd probably flatten out the require files and do it in the main file controlling the player actions and explicitly name the functions with what is needed to run it (in this case...the tree).
Keeping mostly your coding conventions, my slight refactor would look something like:
index.js
const player = require('./scope_test_player');
const apple_tree = require('./scope_test_apple_tree');
player.lookAtTree(apple_tree);
player.waterTree(apple_tree);
scope_test_player.js
module.exports = {
lookAtTree: function(tree){
console.log(
'The apple tree is '+tree.height+'ft tall and has '
+tree.apples.length+' apples growing on it'
);
},
waterTree: function(tree) {
tree.grow();
console.log('The apple tree grew to', tree.height, 'in height')
}
};
scope_test_apple_tree.js
module.exports = {
height: 10,
nutrition: 0.3,
apples: [],
fertilize: function(number) {
this.nutrition += number;
},
grow: function() {
this.height += this.nutrition;
}
};
Yes, I had circular dependencies in my code because I was unaware of the danger they imposed. When I removed them from the main project sure enough it started working again. It now seems that I'm going to be forced into redesigning the project as having two modules randomly referencing each other is going to cause more problems.
I'm having an issue with RequireJS. Essentially, I'm not able to access a function defined inside another file from another one.
I need to do that because I want to export a given subset of functions like
define('submodule', [], function() {
let myFunction1 = function(){ return "Hello"; }
let myFunction2 = function(){ return " From"; }
let myFunction3 = function(){ return " Submodule!"; }
return {
myFunction1 : myFunction1,
myFunction2 : myFunction2,
myFunction3 : myFunction3,
};
});
And accessing them from another file
define('main', ['config', 'sub1', 'sub2', 'submodule'],
function(config, sub1, sub2, submodule) {
//Config
alert(config.conf);
//Submodule
let callSubmodule = function() {
alert(submodule.myFunction1() +
submodule.myFunction2() +
submodule.myFunction3());
}
//sub1
let callSub1 = function() {
alert(sub1.myFunction1());
}
//sub2
let callSub2 = function() {
alert(sub2.myFunction1());
}
});
The fact is that usually I'm able to do this with sub1 and
sub2, but, with submodule, I simply can't. I think it's somehow caused by the dependencies in require.config.js.
My require.config.js:
require(['common'], function () { //contains vendors
require(['config'], function () { //contains a js config file
require(['main'], function () { //main file
require(['sub1', 'sub2'], function () { //some subfiles
require(['submodule']);
});
});
});
});
For submodule.myFunction1() and othe two related functions I'm getting:
Uncaught (in promise) TypeError: Cannot read property 'myFunction1' of undefined
This is weird since I'm able to do that in other situations and I really can't understand why this is happening. For instance, I'm able to call sub1 and sub2 functions from main and other files but not submodule in particular.
Index.html
//Taken from Plunker
. . .
<script data-main="common" data-require="require.js#2.1.20" data-semver="2.1.20" src="http://requirejs.org/docs/release/2.1.20/minified/require.js"></script>
<script src="require.config.js"></script>
. . .
<button onclick = "callSubmodule()">Call Submodule</button>
<button onclick = "callSub1()">Call Sub1</button>
<button onclick = "callSub2()">Call Sub2</button>
common.js contains vendors, here's just an example
requirejs.config({
baseUrl : "",
paths : {
"jquery" : "http://code.jquery.com/jquery-latest.min.js"
}
});
sub1.js
define('sub1', ['submodule'], function(submodule) {
let myFunction1 = function(){ return "called sub1"; }
return {
myFunction1 : myFunction1
};
});
sub2.js
define('sub2', ['submodule'], function(submodule) {
let myFunction1 = function(){ return "called sub2"; }
return {
myFunction1 : myFunction1
};
});
I set up a Plunker with #SergGr help that tries to replicate application's structure but all the modules get undefined on click. On the real application this does not happen.
How can I solve this?
This is your code:
define('main', ['submodule'], function(submod) {
console.log(submodule.myFunction());
});
You have submod in the parameter list. But you then try to access submodule. Note that you return the function straight from your module (return myFunction), so your module has the value of the function myFunction and thus the module is what you should call. The code should be:
define('main', ['submodule'], function(submod) {
console.log(submod());
});
I Managed to solve this issue. Essentially, it was caused by a circular-dependency between the modules. So, a needed b and b needed a leading to one of them being undefined on the dependency resolution.
I found a solution to that on the answer provided by #jgillich at requirejs module is undefined.
So, I managed to solve using, in main
define('main', ['config', 'sub1', 'sub2', 'require'],
function(config, sub1, sub2, submodule, require) {
//Config
alert(config.conf);
//Submodule
let callSubmodule = function() {
alert(require('submodule').myFunction1() +
require('submodule').myFunction2() +
require('submodule').myFunction3());
}
});
As #jgillich said:
If you define a circular dependency ("a" needs "b" and "b" needs "a"), then in this case when "b"'s module function is called, it will get an undefined value for "a". "b" can fetch "a" later after modules have been defined by using the require() method (be sure to specify require as a dependency so the right context is used to look up "a"):
//Inside b.js:
define(["require", "a"],
function(require, a) {
//"a" in this case will be null if "a" also asked for "b",
//a circular dependency.
return function(title) {
return require("a").doSomething();
}
}
);
http://requirejs.org/docs/api.html#circular
The way you've named your modules I would expect they all came from a require config file. I would not expect that requirejs would know how to load those files without some sort of explicit compilation process. I also suspect that your server is returning something due to a 404 that JS is almost able to interpret without exploding.
Your setup seems and naming scheme seems quite strange. If you have the ability to start from scratch below are my recommendations.
Recommendations:
I'm noticing that you're using absolute paths. I highly recommend using relative paths for everything. There are many reasons for this.
Your data-main should be what you call "require.config.js". Your common.js is actually a require.config.js.
You load require.config.js (which is your main) separately using a script tag. You can do this but it's strange.
You can use the "commonjs" style syntax to require files without needing to use the array to define all your dependencies. I recommend that.
This is my recommendation for a set-up:
index.html
<script src="/js/config.js" />
<script src="http://requirejs.org/docs/release/2.1.20/minified/require.js" />
<script>
require('/js/main', function(main) {
main({});
});
</script>
/js/config.js
// setting requirejs to an object before its loaded will cause requirejs to use it as the config
window.requirejs = {
baseUrl : "/",
paths : {
"jquery" : "http://code.jquery.com/jquery-latest.min.js"
}
};
/js/main.js
define(function(require) {
const sum = require('./sum');
return (a, b) => sum(a, b);
});
/js/sum.js
define(function(require) {
return (a, b) => a + b;
});
Update (March 02, 2017)
Your plunker obviously will not work because you have direct calls from HTML to your module functions.
<button onclick = "callSubmodule()">Call Submodule</button>
<button onclick = "callSub1()">Call Sub1</button>
<button onclick = "callSub2()">Call Sub2</button>
RequireJS doesn't work that way. One of key purposes of RequireJS is to provide modules isolation and thus it just can't work that way: imagine if several different modules had functions callSubmodule.
To the best of my knowledge there is no way to bind calls from HTML back to the code in a RequireJS module, it should be other way around: module binds to HTML. And if you fix those issues, everything works fine for me as you can see at this fork of your plunker.
Old Answer
The bug is in your subModule.js
define('submodule', [], function() {
let myFunction = function(){ return "Hello"; }
//return myFunction; // old, wrong
return { myFunction: myFunction };
});
Even if you want to return just 1 function you should not return it as is, you should wrap it into an object and give it an explicit name.
P.S. if this is not your real issuse, please provide us real Minimal, Complete, and Verifiable example
I am using require.js to organize my js:
define([
'underscore',
'sylvester',
'glUtils',
'GLFacade',
'Item',
'Attribute',
'Buffer',
], function(
_,
sylv,
glUtils,
GLFacade,
Item,
Attribute,
Buffer
) {
"use strict";
function Sprite() { this.init.apply(this, arguments); }
_.extend(Sprite.prototype, {
init: function(prog, img, viewPort) {
this._frameNum = 0;
this._framesPerAnimation = 4;
this._prog = prog;
this._viewPort = viewPort;
this._img = new ImageWrapper(img);
//...other initialization stuff...
},
//...other methods...
});
return Sprite;
});
but I consistently run into the error that I forget to add a module to the top of the file. Above I've forgotten to add ImageWrapper to my dependencies. When I do this, my code silently fails with no error messages, even though ImageWrapper is undefined. If I try to log console.log(ImageWrapper) I do indeed get an error.
Why doesn't the constructor call to new ImageWrapper(img) fail with an error? And is there something similar to "use strict;" that I can use to increase the error information during development?
You could lint your code using a tool like http://jshint.com/ - you will get something like:
One undefined variable
27 ImageWrapper
Depending on your setup there are different ways to automate this, some editors have built this in or plugins can extend this functionality. There also is a command line version on npm if you want to run jshint manually: https://npmjs.org/package/jshint
Your code should throw an error but only if you instantiate a new Sprite.
When I try to simplify your code like this
define('Sprite', ['underscore'], function(_) {
'use strict';
function Sprite() {
this.init.apply(this, arguments);
}
_.extend(Sprite.prototype, {
init: function() {
this._foo = new DoesntExist();
}
});
return Sprite;
});
require(['Sprite'], function(Sprite) {
var sprite = new Sprite();
});
it throws a ReferenceError as expected.
I'm currently building a library in Javascript and really like Google's DevTools for debugging it. Unfortunately I don't want my library to log when I release.
This is how my logger is currently setup.
var debug = false;
var increaseSomething = function()
{
// Random Code...
if (debug) { console.log("Increased!"); }
}
Unfortunately this is quite annoying, I shouldn't have to check if debug is on before logging to the console every call.
I could try to encapsulate the console in my own logging object but I feel that wouldn't be such a great idea. Any thoughts?
You could do this?
if (!debug) {
console.log = function() {/* No-op */}
}
As you mentioned, you might not want to kill all logging for everyone. This is how I usually go about it. Define these in some utility file, as global functions. I usually add additional functions for LOG, WARN, ERROR and TRACE, and log these based on a verbosity level.
// Define some verbosity levels, and the current setting.
_verbosityLevels = ["TRACE", "LOG", "WARN", "ERROR"];
_verbosityCurrent = _verbosityLevels.indexOf("LOG");
// Helper function.
var checkVerbosity = function(level) {
return _verbosityLevels.indexOf(level) <= _verbosityCurrent;
}
// Internal log function.
var _log = function(msg, level) {
if(!debug && checkVerbosity(level)) console.log(msg);
}
// Default no-op logging functions.
LOG = function() {/* no-op */}
WARN = function() {/* no-op */}
// Override if console exists.
if (console && console.log) {
LOG = function(msg) {
_log(msg, "LOG");
}
WARN = function(msg) {
_log(msg, "WARN");
}
}
This also allows you to add important information to your log, such as time, and caller locations.
console.log(time + ", " + arguments.callee.caller.name + "(), " + msg);
This may output something like this:
"10:24:10.123, Foo(), An error occurred in the function Foo()"
I thought about encapsulating the console logger again and instead of coming up with an entire object to encapsulate the console I created a function that takes in a console method. Then it checks if debugging is on and calls the function.
var debug = true;
var log = function (logFunction) {
if (debug) {
logFunction.apply(console, Array.prototype.slice.call(arguments, 1));
}
};
var check = function (canvas) {
log(console.groupCollapsed, "Initializing WebGL for Canvas: %O", canvas);
log(console.log, "cool");
log(console.groupEnd);
};
check(document.getElementById('thing'));
I do like #Aesthete's ideas but I'm not yet wanting to make the encapsulated console.
Here is the jsfiddle as example: http://jsfiddle.net/WRe29/
Here I add a debugCall to the Objects prototype. Same as the log function just a different name so theirs no 'overlap' Now any object can call debugCall and check its debug flag.
Object.prototype.debugCall = function(logFunction)
{
if (this.debug) { logFunction.apply(console, Array.prototype.slice.call(arguments, 1)); }
};
var Thing = { debug : true /*, other properties*/ };
Thing.debugCall(console.log, "hello world");
EDIT:
My initial thoughts were to use an object as the 'configuration' to indicate whether the object should be logging. I've used this a while and liked the configuration concept but didn't think everyone would be so keen to use configuration objects in their code alongside a function being passed to a extended function on object. Thus I took the concept and instead looked at function decoration.
Function.prototype.if = function (exp) {
var exFn = this;
return function () {
if (exp) exFn.apply(this, arguments);
};
};
var debug = false;
console.log = console.log.if(debug);
console.group = console.group.if(debug);
// Console functions...
myFunction = myFunction.if(debug);
It's very simple almost unnecessary to even have a decoration function that checks an expression but I am not willing to put if statements everywhere in my code. Hope this helps someone out maybe even spark their interest with function decoration.
Note: This way will also kill logging for everyone unless you setup the if extension correctly ;) *cough some type of object/library configuration indicating debug
https://github.com/pimterry/loglevel
Log level Library::Try whether this suits ur need.
So I am trying to consolidate a bunch of code into some nice NameSpaced functions, but am having a tough time getting it to all work together. For example, I have this (edited down for clarity):
YW.FB = function() {
return {
init: function(fncSuc, fncFail) {
FB.init(APIKey, "/services/fbconnect/xd_receiver.htm");
FB.Bootstrap.requireFeatures(["Connect"]);
if(typeof fncSuc=='function') fncSuc();
},
login: function(fncSuc) {
this.FB.Connect.requireSession(function() {
if(typeof fncSuc=='function') fncSuc();
});
},
getUserInfo: function() {
var userInfo = new Object;
FB.Facebook.apiClient.users_getInfo([FB.Facebook.apiClient.get_session().uid],["name"],function(result, ex){
userInfo.name = result[0]['name'];
userInfo.uid = result[0]['uid'];
userInfo.url = FBName.replace(/\s+/g, '-');
return userInfo;
})
}
};
}();
On a normal page I can just do:
FB.init(APIKey, "/services/fbconnect/xd_receiver.htm");
FB.Bootstrap.requireFeatures(["Connect"]);
var userInfo = new Object;
FB.Facebook.apiClient.users_getInfo([FB.Facebook.apiClient.get_session().uid],["name"],function(result, ex){
userInfo.name = result[0]['name'];
userInfo.uid = result[0]['uid'];
userInfo.url = FBName.replace(/\s+/g, '-');
return userInfo;
})
And it works.
I have been trying to do:
YW.init();
YW.login();
YW.getUserInfo();
But it doesn't work. I keep getting 'FB.Facebook is undefined' from YW.getUserInfo
I could be doing this all wrong too. So the FB.init, FB.Facebook stuff is using the facebook connect libraries. Am I doing this all wrong?
If you look at the JavaScript that your browser has parsed in Firebug or a similar web debugger do you see the Facebook Connect JavaScript there? Looks like it's not in scope, and since FB is at the global level that means it's not in scope at all. Has nothing to do with namespaces. Global in JavaScript is global everywhere.