Duplicate constants between Javascript and server-side code

综合技术 2018-05-18

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.

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.

Hello, buddy!

责编内容by:Hello, buddy! (源链)。感谢您的支持!

您可能感兴趣的

Veille de la semaine #25 de 2018 Finding a front-end for Symfony (en) : Quelques statistiques intéressantes sur les t...
Go 1.11: WebAssembly for the gophers In February 2017, the issue for WebAssembly support was opened at golang/go b...
FEX 技术周刊 – 2018/01/01 微信搜索『FEX』关注我们的公众号,及时获得最新资讯。 深阅读 Top JavaScript Libraries & Tech to Learn in 2018 ...
Create Custom Scrollbars With Pure JavaScript – sc... Demo Download Author: akzhy Views Total: ...
Custom alerts: What you set is what you get Dynatrace offers powerful artificial intelligence that automatically detects performance anomalies i...