admin管理员组文章数量:1296884
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 ments 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:
- Use a shared constants source file, if you're lucky and the syntax for both languages is patible.
- Dynamically generate a constants file for one of the languages based on the other, as part of the build process.
- Generate all JavaScript through a templating language.
- Put shared constants inline in the HTML, rather than putting them in JavaScript file.
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 ments 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:
- Use a shared constants source file, if you're lucky and the syntax for both languages is patible.
- Dynamically generate a constants file for one of the languages based on the other, as part of the build process.
- Generate all JavaScript through a templating language.
- Put shared constants inline in the HTML, rather than putting them in JavaScript file.
- Hmm, would using a JavaScript framework help with this kind of work? – summea Commented Apr 22, 2014 at 18:48
- This isn't really variable passing, it's all statically piled, just uses variables that are duplicated across both projects. – user202987 Commented Apr 22, 2014 at 18:52
- what's the server side language? – hunter Commented Apr 22, 2014 at 18:52
- 1 Python, but I imagine the same question could apply to any language. – user202987 Commented Apr 22, 2014 at 18:54
-
I would vote for #2. Using python, this does not seem to hard: keep your constants in a class, and at build-time (or deploy-time), json-ify its contents to a
.js
file readingvar constants = {jsonified-constant-definitions-here};
which would be referenced from the same html that loads your current JS. – tucuxi Commented May 19, 2014 at 12:33
6 Answers
Reset to default 1I 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.
I wrote a Python tool called Reconstant to solve this exact problem.
Here is an example input file test.yaml
:
constants:
- name: SOME_CONSTANT
value: "this is a constant string"
- name: OTHER_CONSTANT
value: 42
enums:
- name: SomeEnum
values:
- A
- B
- C
- name: OtherEnum
values:
- FOO
- BAR
outputs:
python:
path: autogenerated_constants.py
javascript:
path: autogenerated_constants.js
c:
path: autogenerated_constants.h
Now you run reconstant test.yaml
and the following output files are generated:
autogenerated_constants.py
# autogenerated by reconstant - do not edit!
from enum import Enum
# constants
SOME_CONSTANT = "this is a constant string"
OTHER_CONSTANT = 42
# enums
class SomeEnum(Enum):
A = 0
B = 1
C = 2
class OtherEnum(Enum):
FOO = 0
BAR = 1
autogenerated_constants.js
// autogenerated by reconstant - do not edit!
// constants
export const SOME_CONSTANT = "this is a constant string"
export const OTHER_CONSTANT = 42
// enums
export const SomeEnum = {
A : 0,
B : 1,
C : 2,
}
export const OtherEnum = {
FOO : 0,
BAR : 1,
}
autogenerated_constants.h
// autogenerated by reconstant - do not edit!
#ifndef AUTOGENERATED_CONSTANTS_H
#define AUTOGENERATED_CONSTANTS_H
// constants
const char* SOME_CONSTANT = "this is a constant string";
const int OTHER_CONSTANT = 42;
// enums
typedef enum { A, B, C } SomeEnum;
typedef enum { FOO, BAR } OtherEnum;
#endif /* AUTOGENERATED_CONSTANTS_H */
This doesn't yet support all the languages you mentioned, but it is very easy to add support for a new language. The Python output shown above is implemented in nine lines of code and the C output (which is the most plicated) is implemented in thirty lines of code.
option1 environment variables
This would depend on your exact setup, but I would use environment variables for those constants as most languages and build tools already support it.
Then have a .env file that gets pulled from a mon location I both projects.
option2 config api endpoint
Another option is to have an api endpoint serving those constants and either use them for the front-end at build time, or even at run-time depending I the specifics of your use case
I created a constant table which consisted of Key value pairs. Using dot core I read it at initialization time, using DI I created a singleton of the key value pairs and then sent it to the Angular front end. If a literal value needed updating in was done in the table, keeping my C# and JavaScript in sync and no redeployment was necessary.
This largely depends on what server technology you use and how you are defining those variables, but it's a good idea in general to have a collection of key-value pairs, so you will have no trouble extending it with new values. For example you could do this in PHP:
$array = [
'key1' => 123,
'key2' => 456,
'key3' => 789,
];
>?
<script>
<?php
foreach ($array as $key => $value) {
?>
let <?php echo $key; ?> = <?php echo is_string($value) ? "'" . $value . "'" : $value; ?>;
<?php
}
?>
</script>
Or you could even call json_encode
. If you use some other server-side language, the idea remains the same. If you consider your variables as key-value pairs, then you can loop them or convert them into JSON and generate Javascript variables into your HTML.
Integration tests can be a great tool to solve this problem.
Create a test suite which hits your API and pares the returned object & variables with the objects/variables defined in your JavaScript. You can create this API endpoint with some reflection magic and include metadata to simplify this parison or pare other information, too.
Then have your integration test suite run on a continuous integration server, maybe triggered by a mit both on the JS or the API/server side, and automatically inform you of test failure.
本文标签: Duplicated constants between Javascript and serverside codeStack Overflow
版权声明:本文标题:Duplicated constants between Javascript and server-side code - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741614677a2388459.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论