What is the method for assigning a string to module variable definitions?

As someone new to TypeScript and MVC, I find myself unsure if I am even asking the right questions. I have multiple TypeScript files with identical functionality that are used across various search screens. My goal is to consolidate these into a single file by passing the search screen name and area (both strings) to it. Is there a way to achieve this by sending this information from the view to the TypeScript file?

To provide some context, here is a snippet of my TypeScript code:

module HarSearch {
    const area = "";
    const searchScreen = "";
    const gridName = searchScreen + "SearchGrid";
    const searchGrid = $(`#${gridName}`);
    const gridOptionsStorageName =  searchScreen + "GridOptions";
    const filtersStorageName =  searchScreen + "SearchFilters";
    const filterFormName = "formFilters";
    var defaultGridOptions: kendo.ui.GridOptions;

    $(function(e) {
        var harSearchGridData = searchGrid.data("kendoGrid");
        KendoGridFunctions.resizeGrid(searchGrid, -25);
        defaultGridOptions = harSearchGridData.getOptions();
        loadSearchState();
    });

    // additional functions...
}

I am specifically looking for ways to set the values for 'area' and 'searchName' dynamically.

EDIT: Taking Paleo's advice into consideration, I have made some changes to my code by moving the necessary variables into their own class. However, I still need a mechanism to assign values to these variables.

class definitions {
    public static area = "";
    public static searchName = "";
}

module HarSearch {
    const area = definitions.area;
    const searchName = definitions.searchName;
    .
    .
    .
    // remaining code remains unchanged
}

Answer №1

After some experimentation, I arrived at a solution that is functional, though not perfect. Rather than separating my variables into their own class, I decided to keep them within the module. To achieve this, I included a script in my view that sets global variables used by the module. In this setup, Model.SearchArea and Model.SearchName are simple strings.

VIEW

<script type="text/javascript">
    $(function() {
        searchArea = @Html.Raw(Json.Encode(Model.SearchArea));
        searchName = @Html.Raw(Json.Encode(Model.SearchName));
    })
</script>

TS File

module Search {
    declare var searchArea: string;
    declare var searchName: string;
    var gridName: string;
    var searchGrid: JQuery;
    var gridOptionsStorageName: string;
    var filtersStorageName: string;
    const filterFormName = "formFilters";
    var defaultGridOptions: kendo.ui.GridOptions;

    $(() => {
        gridName = searchName + "SearchGrid";
        searchGrid = $(`#${gridName}`);
        gridOptionsStorageName = searchName + "GridOptions";
        filtersStorageName = searchName + "SearchFilters";

        var searchGridData = searchGrid.data("kendoGrid");
        KendoGridFunctions.resizeGrid(searchGrid, -25);
        defaultGridOptions = searchGridData.getOptions();
        loadSearchState();
    });

    .
    .
    .
    //more functions
}

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

Inheriting Components from Templates

Insight on Motivation There are countless situations where we may require multiple components to share the same functionalities. It is not ideal (and definitely shouldn't be done!) to simply copy child components. This is where the concept of inherit ...

Google Maps integrated AWS server

While utilizing an AWS server for my application, I have encountered a difficulty with Google Maps. When running my application using localhost, Google Maps functions perfectly fine. However, when attempting to run the application using an IP address, it f ...

RTK Query - executing a query upon mounting with lazy loading enabled

Should rerendering be triggered by sending a request on mount? Or is the use of useEffect necessary? (Is lazy mode different from regular queries?) export const Catalog: React.FC<CatalogProps> = ({ object, category }) => { const [getCatalogPro ...

How can I obtain the index of the selected class name?

Is there a way to retrieve the index of a classname assigned to multiple input fields and then log it using console.log()? I've written this code snippet: document.querySelectorAll('.class-name').forEach(item => { item.addEventListene ...

Position a BoxGeometry in a straight line between two points in 3D space

In my game, I have the ability for players to add objects to a world without being restricted to a grid. Now, I am working on adding footpaths to the game. When the player clicks on "Create footpath", they can add a point in the world at the location of th ...

Tips on retrieving and refreshing dynamically generated PHP file echo output within a div

I have a div that I'm refreshing using jQuery every 10 seconds. The content is being read from a PHP file named status.php. Here is the JavaScript and HTML for the div: <script> function autoRefresh_div() { $("#ReloadThis").load("status.php ...

Using a jQuery UI accordion with a numbered list

As part of my company's user documentation, I am trying to integrate jQuery UI components into our HTML output. Despite my limited experience with JavaScript, I was able to get the accordion feature working for table rows. However, I am now facing dif ...

What could be causing my node.js to fail in producing a true result within the return statement?

I've encountered an issue with VS code where the return true command is not displaying anything in my terminal, while console.log(map[arr2[j]]) successfully returns true. I'm unsure if this problem lies with node or my terminal. How can I ensure ...

What is the best way to identify a specific AdWords account while utilizing campaignSelector within AdWords scripts?

I have been working on a script that aims to achieve the following tasks: Go through all the accounts in an MCC and pick out the ones with 'SEM' in their name. Go through the campaigns in a selected account and choose those that meet specific c ...

Run JavaScript code before finalizing the "submit" action within a Ruby on Rails application

Having trouble with utilizing old JS scripts found on Stack Overflow. <div class="form-actions"> <%= f.button :submit, class:"btn btn-success create-campaign" %> </div> The submit button is causing an issue for me. <div clas ...

Loop through the JSON data and display any empty strings

I encountered an issue while trying to convert an object string from a list of arrays using the JSON.parse method. Despite successfully converting the object string to an object, it appears empty when used within ng-repeat. Jade .item.col-md-4(ng-repeat= ...

Utilizing jQuery to Toggle Visibility of Table Rows on Button Click

I have a unique layout on my page where there are two tables positioned side by side. The table on the left consists of buttons with company names, and the table on the right should display employees associated with each specific company. Upon initially l ...

How can I trigger the rendering of a component by clicking a button in a separate component?

I am currently facing a challenge in rendering a component with an "Edit" button that is nested within the component. I attempted to use conditional rendering in my code, but unfortunately, I am struggling to make it work as expected. Does anyone have any ...

Firefox is mistakenly interpreting a pasted image from the clipboard as a string instead of a file, causing

I am facing an issue where I am attempting to extract images from a contenteditable div using the paste event. The code works perfectly in Chrome but does not function as expected in Firefox. I have implemented the following code: $(window).on("paste& ...

The value returned by a mocked Jest function is ignored, while the implemented function is not invoked

Having an issue with mocking the getToken function within my fetchData method in handler.ts while working with ts-jest. I specifically want to mock the response from getToken to avoid making the axios request when testing the fetchData method. However, des ...

Utilizing AngularJS to effectively group and filter using Ng-repeat

I am working with an array retrieved from an Azure server Log (clicks array) that I need to sort in a specific way. Below is the request: $http({ method: 'Get', headers: { 'Host': 'api.applicationinsights.io&apo ...

Having trouble understanding why my submission button isn't working

I'm struggling to understand why my submit button isn't working correctly. Initially, I had an e.preventDefault() at the beginning and it didn't have any effect. However, after receiving advice from an instructor, I included it in the condit ...

Refresh the HTML webpage using AJAX technology

I am trying to implement a simple html page with a single table that updates in the background every 5 seconds. The traditional solution of using <meta http-equiv="refresh" content="5"> is not suitable as it would disrupt the user experience by displ ...

Custom component not rendering expected CSS style

I have successfully developed a custom web component without using any framework. I then proceeded to populate it with content from a template tag. Although I was able to manipulate the content using JavaScript, I encountered difficulties when trying to m ...

JavaScript can dynamically attach EventListeners to elements, allowing for versatile and customized event

I am currently populating a table using data from an XML file. One of the columns in the table contains links to more details. Due to the unique requirements of my web page setup (Chrome extension), I need to dynamically add an event handler when the table ...