NOTE: The other answers don't seem to work because I am not looking to just import or use a function from another file.
I need to know if there's any way I can put in something anywhere that tells another JS file to run. And the whole file.
I'm new to JavaScript and I'm trying to avoid things like NodeJS and jQuery so that I have a better understanding of JS, so I've tried making some simple programs.
I made a little game, but I want to put in another level. I tried making it so that once the collision is detected in a certain area, it will set a boolean that determines if the level is still running to false. Then I made a while loop that says that if it's on true, it updates the game. The problem is that this can't work as I've learned from other questions on this site. It crashes the whole thing. So I thought that if I can go back to my old game loop but put the other level in the file, I could call that file and have it basically be a separate game.
TL;DR: I need to know how to stop running one file and move onto another in JS, or at least redirect the user to a separate URL so that I can put the level in a separate site.
I am going to read into your question a little bit to give you what I believe to be a better answer. Essentially, you want to change the level a player is on by loading in a new .js file and stopping the use of another.
Multiple files become 'one big file' to the interpreter meaning that putting your levels into separate files is for organizational purposes only - unless you have multiple pages that each use a different 'level.js' file.
You haven't posted any code, so I can't really give you an example tailored to you, but I'll give a general one instead.
The easiest (but worst) practice would be to redirect the player to 'level2.html.' I did this when I first started programming games, so it should be fine for your learning purposes.
if (gameOn == false) {
location.href = "level2.html";
}
Then in level2.html you have a different <script> that runs level 2 along with all of your other game code.
The best (but more difficult) way to do this would be to replace whatever data structure you have that dictates the level with a new one.
Ex: If you have an array that stores a bunch of gameObjects, you could replace that with a 'level2' array.
Feel free to ask any questions.
You may be interested in import and export.
This is a big subject, but to sum it up you need three basic things:
a script tag that references the entry point of your program, typically index.js, which should specifically have a type="module" property like <script type="module" src="./index.js"></script>
the main entry point script/module itself, like index.js, which should have one or more import statement(s)
one or more files to import into your main module like level1.js, level2.js, etc.
All together it may look something like this:
// html
<script type="module" src="./index.js"></script>
(see note 1)
// index.js
// do all game stuff here
import level1 from './level1.js';
import level2 from './level2.js';
// etc.
...
// do something with level1, level2, etc.
// level1.js
export default {
someList: [], // ?
someProperties: {}, // ?
}
// OR ( but be sure there's only one export statement )
export default function () {
// do it, run the level!
}
Notes
I used the relative path ./ to refer to the current folder where everything is. I have seen examples that only contain a forward slash, no dot, but I know that this does not work in Chrome, and I doubt that the dot hurts in other browsers. This also means you can have a folder structure, for example:
game
-> images
-> js
-> source
index.js
-> levels
level1.js
-> css
and refer to a level from index.jslike ../levels/level1.js
Related
When testing using the POM model data pattern, is it best to have the locators for elements in the page object or have them in a separate file like the test data
pageObject
loginPage
homePage
testDate
loginPageData
homePageData
pageLocators
loginPageLocators
homePageLocators
specs
loginTest.js
Many thanks
Everything is good what is good FOR YOU. There is no single right answer. So I'll share my experience utilizing POM in my current project.
No one ever thought of one minor downside of POM: navigation down the chain to get to the bottom locators.
I worked for a while with perfectionists who believed if something is logically different, it should go into a separate file. Thus, we had locators stored separately from elementFinders and methods that interact with pages. This was reasonable, but consider what I need to go through if I debug a failed test:
to find a failed line in a spec and jump in the source code of the method that causes error
This method belongs to extended class and depends on parental class, so I jump in the source of the class
That method interacts with an element, defined somewhere else, so I have to open that file
the element has locator stored in another file, so I need to find that file too
Finally, when I found my locator, I forgot what I was doing, not to mention tediousness of the process and waste of time.
Therefore in my next project, I tried to balance this neatness of the code with overall usability and easiness of navigation between files, and was happy with the way I structured the code
Good luck!
Basically, we have a massive core.js file with lots of jQuery calls that have no structure whatsoever. Example:
$(document).ready(function() {
$(document).on({
change: function() {
// some code specific to 1 view
}
},
"#some-id-name-that-may-exist-in-multiple-views" // like "bank-box"
});
// This code isn't even inside a closure, so it get's executed in all views but '.metadata' only exist in one, braking the whole system.
checkProgress($.parseJSON($('.metadata').text()));
Now, as the comment says, it has happened before that a whole section of the system breaks because of a JS error that usually happens due to the share of JS code. (Ironically, thanks to the sharing of said code, Continuous Integration caught it because of the only 1% of the code that's tested)
How do I justify the usage of separate JS files that holds view-specific logic, instead of a massive core.js that exist because of the "the browser would cache all of the JS on the first load" argument. Any resources or links are welcome.
On the other hand, maybe multiple files is an incorrect approach and we need to have 1 core.js file, but the code should be in a different way so that it doesn't conflict like it does right now. If this is the case, then how.
You can first check for the existence of those elements, that you are working on. You could rewrite your this code like this:
if( $(".metadata").length ){
checkProgress($.parseJSON($('.metadata').text()));
}// if $(".metadata").length
I am learning the source code of hexo, a project based on node.js.
And there is a file init.js:
if (results.config){
require('./plugins/tag');
require('./plugins/deployer');
require('./plugins/processor');
require('./plugins/helper');
require('./plugins/filter');
require('./plugins/generator');
}
why these require statements have no reference? So I checked each index.js under these folder(e.g. tag), the index.js is looking like:
require('./init');
require('./config');
require('./generate');
require('./server');
require('./deploy');
require('./migrate');
require('./new');
require('./routes');
require('./version');
require('./render');
No exports found. I am wondering how these requires work.
I looked at the source you're talking about, and the basic answer to your question is that the code in those requires gets run. Normally, you're right that you need to have some kind of export to make use of objects inside those files, but hexo is being a bit nonstandard.
Instead of having each module be independent and fairly agnostic (except via requires), what they're doing is creating an object called 'extend' (look in extend.js) then each of those individual files (e.g. ./init, ./migrate, etc) require extend.js and hang new objects and functions on it in a sort of namespaced fashion.
If you look at the end of those files you'll see something calls to extend.tag.register and others. Modules are cached when required, so in practice it acts something like a singleton in other languages the way they're doing it.
As Paul points out, the requires you see should be considered as functional units themselves, rather than returning any useful values. Each of the files calls an function to modify an internal state.
I've been reading about the module pattern, but everything I read assumes that the entire contents of the module will be in a single file. I want to have one file per class.
I've resorted to doing this at the top of every file:
if(window.ModuleName === undefined) { window.ModuleName = {}; }
ModuleName.ClassName = function () { ... }
But this allows files to be included without their dependencies, which is also annoying. For example, lets say there is ClassA which uses ClassB, and "ClassB.js" is left out of the HTML, then ClassA will throw up errors. As far as I'm aware Javascript lacks an import statement, so in this case I actually want everything to be in a single file.
I assume that large javascript projects are broken up into multiple files, so there has to be a way around this. How is it generally done? Is there some tool that will combine multiple class files into a single module file?
This is a big topic but let me explain as much as I can. Javascript requires that you have preloaded anything you intended to use, which is why your module pattern has all the "things" in the same file. But if you plan to separate them in different files then you have to manage it before using. I suggest the following approaches
Concatenate them before serving them in the server. For example in jsp, you can create a servlet that returns contenttype = "text/javascript", inside that servlet you can append all the scripts you need in one dynamically generated script then return it to the client.
In your ant or maven builds etc, there are configurations where in you can concatenate them the files you want together. This is a common practice therefore you should find many reference in the internet.
Lazy-load javascripts. This is my preferred way. I use Lazyload javascript library. Basically I declare the dependencies of certain codes much like "import" in Java, then before i call any of them i load their dependencies. This allows for optimized dependency loading without scripts redundancies. The problem is you need to write some fairly complicated scripts to do this.
Hope to help.
I have a bunch of javascript "classes" (Prototype) that make up the inheritance hierarchy of a web application I'm building. I've been trying to organize these classes into "namespaces":
var UI = {
Control: Class.create(KVO.Object,
{
...
})
}
The classes are organized into separate files, so when I wanted to add a class to UI, I did this in a separate file:
UI.TextFieldControl = Class.create(UI.Control,
{
...
})
But, when I try to use UI.TextFieldControl in my program after including the files, it is undefined. I guess this is a scope problem of some sort, because within the TextFieldControl file it is defined, but as far as I can understand UI.TextFieldControl should be defined after it is included; what am I doing wrong?
Ok, I found the problem; I was including the file that defines UI twice, once before the file that defines UI.TextFieldControl and once after. Thanks for your responses; I was beginning to worry I didn't understand javascript scope at all!
Have you tries using FireBug? Because by the code you provided nothing seems to be wrong. If your file includes are fine. Your controls should be defined.
Use FireBug and check your files and their order of loading. Maybe your UI.Control is being loaded after you define TextFieldControl? You'll also be able to see your UI namespace if it hass all the necessery classes and also try defining them by hand and see what happens.
If you're using IE you probably forgot to remove some trailing comma, that simply discarded the whole file with your TextFieldControl...