Organizing large javascript files [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I've started to accumulate quite a few lines of Javascript code for a website. Everything has been in one file so far and that file is becoming impossible to maintain. If there is an error in one line, the entire file breaks.
I've tried splitting the code up into multiple files but there are some shared methods across objects like: validateEmail(address).
Right now, I have my code organized into objects, like so:
var ProductPage = {
addToCartBtn: "#add-to-cart",
init: function() {
ProductPage.initAddToCartPopup();
ProductPage.initSidebar();
...
},
...
};
Then, I call ProductPage.init() on $(document).ready.
My issue is: when splitting ProductPage into a separate file as ContactPage, for example I cannot access ContactPage.validateEmail(). I believe this is because my code is wrapped in jQuery's:
(function ($) {
...
})(jQuery);
Does anyone have insight on how they have organized large systems of Javascript? Also, I plan on doing optimization with putting all of this into one file and compressing it. So, any method which will benefit both maintainability and ease of optimization would be awesome.

validateEmail like methods are functional in my opinion. By functional I mean, y = f(x). These functions are not changing the state but returning an output which are being computed on the passed input.
You might want to keep all this utility functional methods in a separate module and tag it to a global namespace. Make sure to load this(these) utility module(s) before utilizing them.
You can use require.js for dependency management.

Related

Is it ok to create global URL variables? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I have a number of scripts that I need to pass a url parameter to. I also have a number of pages that (static) pages that require me to hardcode the domain/subdomain of the local environment.
What I want to do is store the url within a global variable so that I have to change the url in 1 place to feed the various scripts downstream that rely on it.
I thought about a simple globals file that contains, for example:
var myURL = 'http://www.google.com'
I'll have additional urls, but I plan to follow in kind with those.
I've heard that this is not good practice, but what's the alternative given what I'm trying to do?
If you really have to have some global configuration, I'd stick it in an object / class so you could restrict your use of global variables to the minimum necessary, e.g.:
var Config = {
googleUrl: 'https://google.com',
otherUrl: 'http://example.com',
};
That would be better than having a global variable for each thing.
I've heard that this is not good practice, but what's the alternative given what I'm trying to do?
It might be worth explaining your use case a little more. For instance is it appropriate for these URLs to live in JavaScript configuration or do they belong to a specific UI component? If so should the UI component specify the URL on a HTML element as a data-attribute? If they belong with a specific JS module, should they be local variables for that module?
I also have a number of pages that (static) pages that require me to hardcode the domain/subdomain of the local environment.
Could you not use window.location.hostname for those?
I might be wrong, but I don't know why this should be a problem, as long as you are using constants.
const name1 = value1 [, name2 = value2 [, ... [, nameN = valueN]]];
Edit:
But at the end you should avoid using global variables, because they could cause some problems at later debugging.

How would a JS module be created? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I'm a little confused on what to do here. I've seen a lot of people create modules in JS, but everyone usually does it differently. I've seen people wrap their WHOLE module in a (function(){})(); , or they declare an object literal, or do something crazy like window.Module = {};. I want to know what would be the best choice to be used (as in what you would think is most useful). Help would really be appreciated, and thanks.
There is only one official solution to create JavaScript modules. Anything else you have seen is either a polyfill for that solution, or a pale echo of the real thing.
The basic syntax is like so:
import otherStuff from "otherStuff.js";
var myThing = {};
myThing.stuff = function(){ /*...*/ };
myThing.do = function(){ otherStuff.doOther(); );
export default myThing;
It can get much more complicated, but the basics are:
Your module must be in a unique file. A file is a module.
Your module should probably export something, although this is not strictly necessary.
This is coming down the pipeline in JavaScript. Unfortunately, no one has been able to agree on the official specification of how to load the modules, so they are not on a track for any near-future release. That said, the specification is under development, and a polyfill that implements it has been created.
Your best bet to use the official module syntax is to run it through BabelJS and compile to a shim like Require (which uses the AMD format) so you can use it without the loader specification.
You can read more about the syntax here and here.
I would say : It depends on the final usage of your "module". If it's something that will be used internally, which means that no one else outside your business will use it, then anything can be used as long as you all agreed on the proper method. Otherwise, if it would be used by others : less global variables you create, better it is. As example, jQuery use "$" and "jQuery" as global variables (maybe others, but I'm not sure). When people adds modules to it, they always add them to window.jQuery.[Under jQuery var] where [Under jQuery var] shall be read on jQuery documentation for proper use.

JS: RequireJS strategy: require once or each time it is necessary? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
There is something I am confused while writing modern JS (ECMA6, NodeJS, React Native)
I have a core file, which requires most of the content I need, say app.js:
var dependency1 = require('dependency1');
var dependency2 = require('dependency2');
And in subfile1.js, I'll need to access dependency1 too. I see two ways to achieve this:
Solution 1: require once and forward to others
Should I write in app.js:
var subfile1 = require('./subfile1')(dependency1);
and in subfile1.js:
module.exports = function(dependency1) {
var subfile1;
// do many things;
return subfile1;
}
Solution 2: require each time
OR in app.js
var subfile1 = require('./subfile1');
and in subfile1.js:
var dependency1 = require('dependency1');
module.exports = subfile1;
Comparison
My intuition is that it is cleaner to use solution #1, because it builds only one instance of each dependency.
But on the other hand, it is much more painful to write, especially when dependencies start to become numerous.
Also it fails at the black-box effect, which is often appreciated when writing independent modules.
My understanding is that both solutions shouldn't make a difference iff the module is completely stateless (ie. not calling var dependency1 = new Dependency1()).
Which brings me several questions:
How can we be sure it is actually the case?
When I am writing modules, should I keep this in mind?
When using external modules, shouldn't the author precise whether it is stateless or not?
Is there a best practice out-there? (writing functional code?)
Ain't there a risk this becomes even less true with classes available in ES6?
Is there any impact memory-wise?
Is what I am saying somehow wrong?
Node.js's require internal behavior solves your problems since modules are cached. They will be created once and you retrieve the instance after. You do not have extra problems due to statefulness with your second method but the same behavior (which is, when using stateful modules, good to know).
Furthermore, you should not have to worry about a module dependencies when you want to use it (especially, you should not have to modify your main code when a dependency is added to a submodule, especially when it is not yours).
Therefore #2 is a better approach.
In app.js:
var subfile1 = require('./subfile1');
In subfile1.js:
var dependency1 = require('dependency1');
var subfile1;
// many things
module.exports = subfile1;

Create a global library in javascript, holding both state and behaviour [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I want to create a globally-accessible library myLib in Javascript. My library should do the following
Keep a somewhat persistent variable myLib.tax.
-- It should survive through the handling of a typical browser user event, at least in simple cases. I don't care if it survives longer than that or not.
-- external code should be able to set the value of this variable, either through a setter or otherwise.
Has a function myLib.applyTax(var price).
-- return value is price + myLib.tax.
-- I don't care what it does if either price or tax is not a number.
Lastly, a brief example of how to call this from another file, in such a way that:
-- for example, file A might set the value of the tax, then file B might apply the.
-- this works even though files A and B are unrelated.
The purpose of this question is for me to understand code and state encapsulation and how to use them from elsewhere.
EDIT: For the benefit of anyone seeing this later, what I did not understand when asking this question is that referring from javascript file A.js to javascript file B.js is a difficult problem unless that is enabled externally, for example in the html. For more detail, see How do I include a JavaScript file in another JavaScript file?
From your comments I see you would implement a Singleton Pattern in C# through static methods and data.
In Javascript you can do the same by managing the closures and putting that data into the outermost one, which would then be accessible to all code due to lexical scoping.
But I'd rather avoid singletons every day. Instead, use dependency injection as follows. This is just an example to show the technique, you'll have to code an actual solution yourself.
var lex = (function () {
var privatedata;
function privatemethod()
{
}
return {
publicmethod1: function (arg1, arg2) { ... },
publicmethod2: function (arg1, arg2) { ... },
getPublicData: function () { ... }
};
}());
This incapsulated object is then injected wherever you need it:
function consumerCode(lexicon)
{
...
}
consumerCode(lex); // injects the lex instance into the consumer code
By having only one instance and passing that same instance around wherever you need it, you will have pretty much what you were asking for.
This technique is not limited Javascript but also useful in C#. But in Javascript with loose typing it is especially powerful.

Passing JavaScript data to page, best practices? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm writing a web application where I need to pass some user data to the JS application on page load. I've identified 3 different approaches, and am wondering what is the best practice with regards to this. The data is not particularly sensitive, but it would be best it is somewhat more secure compare to others.
1. Asynchronously load the data
Using something like $.ajax(). I don't like this approach because it usually leads to the whole "loading" phenomenon and I would like to avoid. Have the data ready than make a separate call.
2. Burn the data into the page.
This can be achieved by doing something like this
<script>
var userdata = { somekey: somevalue }
</script>
3. Make a request using script tags
This can be achieved by doing something like this
<script src="server/getdata"></script>
I understand that this is somewhat like the 1st approach since it makes another get request to the server.
My question is, is any of the 3 approaches above different, or better in terms of security. I understand that all 3 methods are not particularly secure, especially since it can be easily sniffed either way, but is any of the above method a better practice than the other 2, and why?
Of the ones you've given, 2 is best, for just the reasons you said. However, I would not add a new global for it. Rather, I would do:
<script type="text/javascript" src="application.js"></script>
to create someGlobal (among other things) then:
<script>
someGlobal.userdata = { somekey: somevalue }
</script>
Another couple methods with the same advantages are:
data attributes. These are the data- ones. You can put arbitrary data, associated with particular elements (sometimes particular elements make sense; otherwise, you can use body).
Hidden form fields.

Categories