Leveraging external variables within JavaScript

In my views.py, I used to have the following structure:

...
if mymodel.name == 'Myname1':
    #do something
elif mymodel.name == 'Myname2':
    #do something else
...

However, I found this method cumbersome because if the names change, I would have to search through all my code to make corrections. So, I decided to centralize these words in a separate file:

hardcoded_words.py:

myname1='Myname1'
myname1='Myname2'
myname1='Myname3'
...

This way, my views.py was updated to:

from myapp import hardcoded_words
...
if mymodel.name==hardcoded_words.myname1:
    #do something
elif mymodel.name==hardcoded_words.myname2:
    #do something else
...

If 'Myname1' changes, I only need to correct one file:

hardcoded_words.py:

...
myname1='Myname1_b'
...

I wonder if there is a better approach for this issue (feel free to share your thoughts). However, my concern lies with JavaScript. Is there a similar way to handle this?

Here’s an example from my javascript.js file:

function myfunction1(myvariable1, myvariable2) {
    switch (myvariable1) {
        case 'Myname1':
            //do something
        break;
        case 'Myname2':
            //do something else
        break;
        ...

Thank you for any insights or suggestions.

Answer №1

If you are in need of having the identical list in javascript, I would suggest creating a view that can be accessed through an AJAX request to retrieve the Python dictionary containing all the necessary values. By doing this, you eliminate any duplication and avoid having to update information in multiple places (Don't Repeat Yourself principle).

Subsequently, ensure that this view is called before utilizing the values in any part of your logic.

It might also be beneficial to reassess the necessity for using "magic" strings within the existing logic.

Answer №2

To achieve the same functionality in JavaScript, you can create a separate file that contains an Object to store your key-value pairs.

Depending on the version of JavaScript you are using, you have the following options:

In ES6:

export const hardcoded_words = {
    myname1: 'Myname1',
    myname1: 'Myname2',
    myname1: 'Myname3'
}

In ES5:

window.hardcoded_words = {
    myname1: 'Myname1',
    myname1: 'Myname2',
    myname1: 'Myname3'
}

Answer №3

In my opinion, it is more advisable to convert your hardcoded words into a dictionary structure like this:

name_mappings = {'myname1'='Myname1'
                 'myname1'='Myname2'
                 'myname1'='Myname3'}

You can then import this dictionary into a basic Django view that you will access through AJAX using a URL such as /api/get_name_mappings/.

This way, you will only have one central 'vocabulary' to maintain instead of managing it separately on the backend and frontend. Additionally, implementing any complex logic would be more efficient to handle on the server side.

The only drawback to this approach might arise when conducting unit tests for your JavaScript code. In such cases, you may need to create some JS-mocks.

Nevertheless, I concur with @Sayse that this method provides better clarity and organization overall.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to locate an ObjectId within an array of ObjectIds using Mongoose (MongoDB)

Currently, my setup involves using nodejs, mongoose (with mongodb as the database), and javascript. Within my database, I have a collection named A which contains the following examples: { "item": "Kitchen", "location": ...

What is the process by which a web browser can access an offline IP address similar to how Jupyter notebook

I recently found myself using Jupyter notebook and started to wonder about its offline functionality. Where is the server located? How are TCP connections established? And how are HTTP requests sent? Similarly, when working on a website project (such as c ...

Discovering child elements within an iframe using Angular and customizing their appearance

Is there a simple and effective way to locate child nodes within an iframe using Angular in order to access the HTML element? Currently, I have implemented the following method: I designated a reference variable within my iframe (#privacyPolicy) <ifra ...

Error message displayed when attempting to send emails through an HTML form obtained from a complimentary template site

Currently, I am in the process of learning to code basic websites but I'm facing some challenges with getting the contact form to function properly. I decided to work with a free template that can be found at this link: and uploaded it to a shared ho ...

Tips on displaying five bootstrap modal popups simultaneously on a webpage

I'm looking to achieve a specific functionality that involves opening multiple bootstrap modal popups on one page simultaneously without overlapping each other. Specifically, I need a button to trigger the opening of five separate modals each containi ...

Tips for displaying a div only when the input value is greater than 0, and hiding it when the value is 0

My goal is to display a div whenever the input contains at least 1 character and hide it when the input is empty. Despite my efforts, I can't seem to make it work no matter what I try. Here is my initial attempt: var input = document.getElementById( ...

"Troubleshooting: The unique key prop is not functioning as expected with a

I am continuously receiving the warning message: Each child in a list should have a unique "key" prop. Even though I have assigned a key with an index number to my element, it does not appear in the HTML when inspecting via dev tools. The key values are a ...

How to structure a multi-dimensional array in JavaScript

I have received JSON data displayed below. [ { "id":5, "entity_id":122, "entity_type":"STUDENT", "edit_type":"UPDATE", "created_by":122, "created_date":"2017-04-04T18:30:00.000Z", "change_log_id":2, "fiel ...

Is there a way to apply an event function after adding elements through append?

When I click the button, a div is appended inside the body. However, I am trying to make it so that when I click on this newly appended div, an alert message pops up. I have tried implementing this with a highlighted area, but have been unsuccessful. How c ...

Jquery Plugin fails to generate dynamic elements effectively

I developed a masking jQuery script that dynamically adds elements to an existing input element. var link = $('<a title="show" role="link" href="#" class="masker-value">show</a>'); wrapper: function() { container = $(container) ...

Ways to verify the presence of isBrowser in Angular 4

Previously, isBrowser from Angular Universal could be used to determine if your page was being rendered in a browser (allowing for usage of features like localStorage) or if it was being pre-rendered on the server side. However, it appears that angular2-u ...

What is the best way to retrieve the following database results after clicking a button with Node.js?

Currently, my Node.js setup is successfully connected to my webpage and pulling data from a MySQL database. I have managed to display the first row of data as button values in the HTML code below. However, what I now want is for the user to be able to cl ...

stop a element from being removed from the document

Is there a way to stop an element from being removed using something similar to preventDefault()? For example: myNode.on("remove", (e) => { e.preventDefault(); }); I have tried using MutationObserver to detect the removal, but so f ...

Setting the button value to a textbox and refreshing the status information (Codeigniter)

How do I pass the value of my "ACTIVE" status attribute to my textbox? I want to update the user's status by clicking the ACTIVE button. The user's status is currently pending. While I can easily pass the userID, I'm facing an issu ...

"Looking to navigate to the bottom or shift focus to the bottom in an Angular application? Here's

In the div, I have added an element and I am looking to automatically scroll to the bottom of the div every time a new element is added. While I know how to achieve this using jQuery, I am unsure of how to do it using AngularJS. The id of the div is testC ...

What is the most efficient method for accessing PostgreSQL database in Django in order to retrieve a list of all users (tab1) who currently have checked out books (tab

I currently have a basic Django application focused on managing a book library system. Under Tab1, the application stores user information: class Readers(Model): last_name = CharField(...) first_name = CharField(...) Tab2 is dedicated to tra ...

Tips for accessing the initial value within JSON curly braces

In my code, there is a function that returns the following: { 'random_string': '' } The value of random_string is an unknown id until it is returned. How can I extract this value in JavaScript? Appreciate any help. Thanks. ...

What is the best way to retrieve text from the p tag and input it into the text field?

Looking to resolve a situation where two identical IDs exist and need to implement some JQuery. The objective is for the input value to automatically update itself based on changes in the text of the p tag. $(document).ready(function(){ ...

Tips for dynamically adjusting the database in Django

Can the active database in Django be switched dynamically? For instance, is it feasible to utilize one database for inserts and updates, then seamlessly switch to another database for read-only operations? ...

AngularJS enables box to smoothly slide up and down when hovered over

I am attempting to create a div that will overlay an image on hover with a slide up and slide down effect. Can anyone provide guidance on how to achieve this without relying on jQuery? I would prefer to utilize only AngularJS in my application. Here is a ...