Code sharing between browser and server (inheritance) - javascript

I am writing a real-time multiplayer browser game in JavaScript. So I'm running JS on the server (Node.js) and in the browser. Because of that I would like to share code between those two contexts.
I decided to devide the code into three parts: Core, Client and Server. As you may have suspected I use Core for code we need on both sides, the Client and the Server.
Until now I have just been extending the corresponding core class, e.g. Client/Player extends Core/Player, which works just fine.
Now I see that for example a Client/Player needs to extend the Core/Player to get the name attribute and at the same time it needs to extend Client/GameObject to get the render() method and the physics attribute.
If it was written in C++, I could try to use multiple inheritance with all its drawbacks. But since it is written in JavaScript, I'm not sure how to solve this. Any ideas?

What I finally did was a hack with kind of a preprocessor. Before start I replace the require("Core/GameObject") in Core/Player with require(context + "/GameObject"). This way I create kind of a "z" which allows me to inherit from both.

Related

Proprietary Web Components

Let's say we have some proprietary web components which were designed and developed for a specific company needs.
Can we safeguard our web components from being used by others? If yes, how?
Note: I am not talking about other developers modifying the component, I am only thinking about others using them straight away in the first place.
It is just JS. All you can do is delay hackers.
The most you can do is use tools like JSObfuscator and JSFuck to make your code as unreadable as possible. But ofcourse experienced hackers have tools also...
Then it dawned me; it is all about adding extra hurdles, and there is one more hurdle we can call to action.
I wrote a nerdy DEV.to blog post about using the URI to encode your Web Components
Basically boils down to NOT putting the Dictionary in the file itself, like Obfuscators do;
but placing the encoding dictionary in the URI (Domain Path even better!):
<script src="element.js?-customElements-define-HTMLElement-"></script>
And executing:
let D = document.currentScript.src.split`-`;
// D = ["element.js?","customElements","define","HTMLElement"];
window[D[1]][D[2]]("my-element",class extends window[D[3]]{ ... });

JS class loader for client & server side

In JS full stack project some classes shared between server and client side. Most of functionality in such classes relevant for both sides (like constants, validate functions, metadata etc.) But sometimes I need different functionality according to side the code running.
Right now to solve this, I using:
naming convention (server side related functions start with __ client only functions starts with _$)
Global function that says if we running on client or server
Many places like this:
this[(isServer()?'__':'_$')+funcName].apply(this, params);
It is working, but code become ugly. I trying to write some kind of class loader, which will replace this logic on construction time and will be seamless.
Is there something similar already exists? If no, what should I afraid of when implementing such functionality?

Extend Android class with generic parameters in NativeScript

I am using NativeScript 2.0 and I would like to create an extension of an Android class like AsyncTask which contains generic parameters.
I know that I can use the extend() method to create an own implementation of a class or interface:
var myRunnable = java.lang.Runnable.extend({
action: null,
run: function() {
this.action();
}
});
But how can I do this for generic classes / interfaces in "pure" JavaScript?
You should be able to extend any interface/class using the same technique. At worst case you can extend Object. To my knowledge at this moment you can't create a interface/class from straight JS as the Java side needs something to base it off of so that the signatures are correct.
However, based on your example; if you are attempting to create a thread or runable in JavaScript; the result will currently fail horribly. NativeScript is currently a single thread, and if you attempt to cause android to attempt to jump back into JS while it is running JS, well lets just say it won't be your friend. :-)
There is a feature request and apparently this is the next big project now that 2.00 has been released. So we should see threads in the near future. There is also a plugin (disclaimer, I'm the author) called NativeScript-webworkers which can give you access to additional JS threads, but the JS threads DO NOT have the ability to interact with the OS like NS does, they are pure JS threads.

Best way to share JS between browser and node.js when using Google Closure compiler

I'm developing a networked application between the browser and a server running node.js. I'm sharing a lot of code right now, but when I actually deploy this I'd like the client to only get client specific code. My options right now are:
1.) Implement any browser/node.js differences using inheritance. I've tried this in a few places and I end up with a lot of classes that are very, very basic customizations of their parent often only partially specializing a single function. This is not a style I like very much because it means a lot indirection when you're trying to find out what's actually going on.
2.) Define a constant like IS_BROWSER at global scope and then check it whenever I need to change code paths on the browser vs node.js. Then closure compile all js with advanced optimizations to remove dead code on the browser (setting IS_BROWSER = true). Are there any problems with this approach assuming I do whatever I need to do to get advanced optimizations going in closure compiler?
3.) ?? I'm open to suggestions.
If you use advanced compilation, any unused code should be removed; if you use the compiler's export system correctly, any server-side code that your client code does not call will not be in the compiled version of the client code.
You could write all of your code in one big blob then, for your client, add one file with contents like
goog.require('my.client.app');
goog.exportSymbol('my.app.entryPoint', my.client.app.entryPoint);
the compiled code will not include anything that is not in the call tree of my.client.app.entryPoint. Likewise, if your compilation only exports a server entry point, client code will be excluded.
The above style is for writing your script to provide some function which will then get called by an inline script; to make the whole thing into a single script you could do something much simpler:
goog.require('my.client.app');
my.client.app.entryPoint();
To verify that you are not getting a lot of dead code in your compilation output, you could play around with something like this: ScriptCover

How do you organize your Javascript code?

When I first started with Javascript, I usually just put whatever I needed into functions and called them when I needed them. That was then.
Now, as I am building more and more complex web applications with Javascript; taking advantage of its more responsive user interaction, I am realizing that I need to make my code more readable - not only by me, but anyone who replaces me. Besides that, I would like the reduce the moments of 'what the heck, why did I do this' when I read my own code months later (yes, I am being honest here, I do have what the heck was I thinking moments myself, although I try to avoid such cases)
A couple weeks ago, I got into Joose, and so far, it has been good, but I am wondering what the rest do to make their chunk their codes into meaningful segments and readable by the next programmer.
Besides making it readable, what are your steps in making your HTML separated from your code logic? Say you need to create dynamic table rows with data. Do you include that in your Javascript code, appending the td element to the string or do you do anything else. I am looking for real world solutions and ideas, not some theoretical ideas posed by some expert.
So, in case you didnt't understand the above, do you use OOP practices. If you don't what do you use?
For really JS-heavy applications, you should try to mimic Java.
Have as little JS in your HTML as possible (preferably - just the call to the bootstrap function)
Break the code into logical units, keep them all in separate files
Use a script to concatenate/minify the files into a single bundle which you will serve as part of your app
Use JS namespaces to avoid cluttering up the global namespace:
var myapp = {};
myapp.FirstClass = function() { ... };
myapp.FirstClass.prototype.method = function() { ... };
myapp.SecondClass = function() { ... };
Using all these techniques together will yield a very manageable project, even if you are not using any frameworks.
I use unobtrusive javascript, so, outside of the script tags I don't keep any javascript in the html.
The two are completely separated.
A javascript function will start when the DOM tree is completed, which will go through the html and add the javascript events, and whatever else needs to be changed.
In order to organize, I tend to have some javascript files that are named similar to the html pages that they use, and then for common functions I tend to group them by what they do, and pick a name that explains that.
So, for example, if I have UI functions then I may call them: myapp_ui_functions.js
I try to put the name of the application in the filename, unless there is some javascript that is common to several projects, such as strings.js.
I have (usually) one file that contains a bunch of functions and that's it. That is included in every page that uses Javascript. In the pages themselves, I'll make the calls to the functions like:
$(function() {
$("#delete").click(delete_user);
$("#new").click(new_user);
});
where delete_user() and new_user() are defined in the external file.
I too use unobtrusive Javascript, which for me means jQuery (there are other libraries that are unobtrusive).
You don't want a separate file for each page. That just means more unnecessary external HTTP requests. With one file—assuming you've cached it effectively—it'll be downloaded once and that's it (until it changes).
If I have a large amount of Javascript or the site is effectively split into multiple areas then I may split the Javascript but that's not often the case.
Also, in terms of my source code, I may have multiple JS files but I'll often end up combining them into one download for the client (to reduce HTTP requests).
More at Multiple javascript/css files: best practices? and Supercharging Javascript in PHP.
I've been rewriting a lot of my reusable code as jQuery plugins. I moved to jQuery from Prototype when I started doing ASP.NET MVC. Overtime I've migrated a lot my reusable code, or at least the ideas, from Prototype-based OO to jQuery-style plugins. Most of these are stored in their own JS files (mainly intranet apps so page load speed is pretty high anyway despite the extra requests). I suppose I could add a build step that coalesces these if I needed to.
I've also settled on a MasterPage approach that uses a ContentPlaceHolder for scripts that is right before the closing body tag. The standard jQuery/jQuery UI loads, and any other common JS goes right before the script placeholder in the MasterPage. I have tiny bit of JS at the top of the MasterPage that defines an array that holds any functions that partial views need to run on page load. These functions are run from the base document.ready() function in the MasterPage.
All of my JS is completely separate from my mark up. Some JS may exist in partial views -- these are encapsulated when the partial may be included more than once to make it specific to that instance of the view -- but generally not. Typically only included in the placeholders so that it's loaded at the bottom of the page.
Also, if you want to go OO heavy, check out mochikit: http://www.mochikit.com/
I find that developing your javascript using OO methodology is the way to go if you want it to be clean, readable and even somewhat secure. I posted the following question
Cleanest format for writing javascript objects
And got some fantastic responses on how to write my javascript code well. If you follow these basic principles you can use almost any library, such as yui, jquery and prototype, with ease.

Categories

Resources