Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicated constants between Javascript and server-side code

Tags:

javascript

web

In my project, I have some of the same variables defined in my JavaScript code as on my server (written in a different language). I have comments that when one side is changed, the other should change as well. This feels like a clumsy way to share these variables.

Is there a standard approach to sharing variables between the JavaScript scripts and the back-end of my website?

Some options I've thought of:

  1. Use a shared constants source file, if you're lucky and the syntax for both languages is compatible.
  2. Dynamically generate a constants file for one of the languages based on the other, as part of the build process.
  3. Generate all JavaScript through a templating language.
  4. Put shared constants inline in the HTML, rather than putting them in JavaScript file.
like image 965
user202987 Avatar asked Apr 22 '14 18:04

user202987


1 Answers

I assume what you're after is single page applications. You can change your backend to be restful, and whenever something needs to be changed, your Javascript can both update itself and inform backend about it.

Have a look at popular javascript frameworks like AngularJS and see how single page applications are being developed. First few tutorials should get you going.

No, you will not be sharing variables directly. You will be sharing what value your variables contain. When one is changed, you will tell your application to update the other.

For example, let's say you have backend which outputs users in JSON format.

{
    "users": [
        {
            "firstName": "John",
            "lastName": "Doe"
        },
        {
            "firstName": "Anna",
            "lastName": "Smith"
        },
        {
            "firstName": "Peter",
            "lastName": "Jones"
        }
    ]
}

You will first initialize this information on a javascript variable. Then, each time an user is (let's say deleted), you need to both remove user from this variable and also inform backend about it, so they will be in sync.

I would like to give you more information about it but I'm sure the very first tutorials of AngularJS will clear many things in your mind.

like image 184
Aristona Avatar answered Oct 14 '22 02:10

Aristona