What is the best way to attach events to buttons using typescript?

Where should I attach events to buttons, input fields, etc.? I want to keep as much JS/jQuery separate from my view as possible. Currently, this is how I approach it:

In my view:

@Scripts.Render("~/Scripts/Application/Currency/CurrencyExchangeRateCreate.js?" + DateTime.Now.Ticks.ToString())

<script>
    var x = new CurrencyExchangeRateCreate();
    var createUrl = @Url.Action("Create", "Currency"),
        indexUrl = @Url.Action("Index", "Currency");
</script>

And in my TypeScript class:

var createUrl, indexUrl;
class CurrencyExchangeRateCreate {
    private form: JQuery = $("#createForm");
    private submitButton: JQuery = $("#submitButton"); 

    constructor() {
        var self = this;
        this.submitButton.on("click", function () {
            self.Create();
        })
    }

    public Create() {
        var self = this;
        var ajaxOptions: JQueryAjaxSettings = {
            async: true,
            url: createUrl,
            data: self.form.serialize(),
            method: "POST",
            global: true,
            success: function () {
                window.location.href = indexUrl;
            },
            error: function () {
            }
        }    
        $.ajax(ajaxOptions);
    }    
}

As you can see, I have a form that can be submitted by clicking a button, but the event for this button click must be bound somewhere. Is it correct to do it in the constructor as I did here, requiring me to instantiate the new class? Are there better ways to handle this?

Answer №1

Consider implementing the following approach:

class CurrencyRateUpdater {
    // Define class properties and methods without event binding.

    private form: JQuery = $("#updateForm");
    private updateButton: JQuery = $("#updateButton");

    // Constructor suggestion:
    constructor(updateUrl, viewUrl) {
      this.updateUrl = updateUrl;
      this.viewUrl  = viewUrl;
    }

    // Make adjustments in the update method:

    public Update() {
        var self = this;
        var ajaxOptions: JQueryAjaxSettings = {
            async: true,
            url: this.updateUrl,
            data: form.serialize(), //<----remove self from here.
            method: "POST",
            global: true,
            success: function () {
                window.location.href = this.viewUrl;
            },
            error: function () {
            }
        }    
        $.ajax(ajaxOptions);
    } 

}


var button = document.querySelector('#updateButton');

button.addEventListener('click', function(e){
    e.preventDefault(); // Prevent form submission.
    var updateUrl = @Url.Action("Update", "Currency"),
        viewUrl  = @Url.Action("View", "Currency");

    var updater         = new CurrencyRateUpdater(updateUrl, viewUrl);
        updater.Update(); // Invoke the update method here.
});

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

The current date is cycling back to the month before

There is a datetime received from my api as 2018-09-01T00:00:00.000Z, referred to as frame.scandate. Another date is generated within the program as 2018-09, simply known as scandate. These examples can represent any year/month combination. In my code: ...

jQuery eliminates the placeholder text in a textarea once the textarea text has been cleared

I'm dealing with a Bootstrap modal that contains a textarea. My goal is for the textarea to be empty every time the modal is opened. However, I've run into an issue where using $('textarea').val('') to clear the text also rem ...

Is it possible to generate a "pop-up" window upon clicking on the register button?

As a backend programmer, I'm looking to create a popup window that appears in front of the current window when users click "register", eliminating the need for redirection to another page. I believe you understand the concept. How can I achieve this? ...

Utilize the serializeArray method in AJAX to send form data, while also implementing validation for each input text field as the user

I'm looking to validate text fields and type="file" input fields individually using the onblur and onchange events. The code I am working with involves AJAX, jQuery, and PHP. Any assistance in resolving this issue would be greatly appreciated. Here i ...

Tips for displaying data by using the append() function when the page is scrolled to the bottom

How can I use the append() function to display data when scrolling to the bottom of the page? Initially, when you load the page index.php, it will display 88888 and more br tags When you scroll to the bottom of the page, I want to show 88888 and more br ...

Exploring the inner workings of the canDeactivate guard feature in Angular

Exploring the concept of guards in Angular has sparked a question in my mind. Why can't we simply have a class with a deactivate method that we can import and use as needed? The provided code snippets illustrate my confusion. export interface CanComp ...

Passing a variable into the highcharts function using jquery and pug is proving to be a challenge for me

I am facing an issue while trying to pass a variable into the Highcharts function using jquery and pug. This variable is essential for setting data in series. In order to tackle this problem, I have created a function called getData in my index.js file whi ...

What is the best way to add content to a box once it has been hovered over?

Looking to create a sticky note-style design, but struggling with displaying the content inside the box only when hovered. In my code example below, can you help me achieve this effect? body { margin: 45px; } .box { display:inline-block; backgrou ...

Why is jQuery not defined in Browserify?

Dealing with this manually is becoming quite a hassle! I imported bootstrap dropdown.js and at the end of the function, there's }($); Within my shim, I specified jquery as a dependency 'bootstrap': { "exports": 'bootstrap', ...

Implementing unique behaviors based on data types in Typescript

I'm currently working on a React project where I need to showcase different types of articles, which I refer to as "Previews." These articles can be either text-based or contain images/videos. To handle this, I've defined two interfaces (TextPre ...

Tips for adding content to a textarea after making manual changes to its existing content

One issue I encountered is with capturing the enter key on an input field and appending it to a textarea. While this works initially, any edits made directly on the textarea seem to disrupt the functionality. How can this be resolved? I have tested this i ...

Tips for resuming a video playback in HTML5 after pausing it for a brief moment

I am working with a video called introVid, and my goal is for it to pause for 2 seconds when it reaches the 1 second mark before resuming playback. Although I've attempted to achieve this using the code below, the video remains in a paused state after ...

Problem with updating an Html.TextBoxFor based on the value of another one

I have been trying to implement a basic jQuery functionality that involves changing the text in one textbox to be half of the numeric value entered in another textbox. Below is the script I am using: <script> $(document).ready(function () { $(& ...

Displaying information stored in the database following the selection of an input from a drop

Join me on a journey through my travel table: +---------+---------+------------------+------------+---------+ | id_tour | region | destination | date_tour | price | +---------+---------+------------------+------------+---------+ ...

Handling empty values in JSON data when sending it to the controller through AJAX

Attempting to transmit the following JSON data from View to Controller: { "allselected": false, "selectedIds": ["", "all"], "targetControl": "Studieniva", "targetSource": "studienivalist", "dependency": [{ "name": "ShopNo", ...

Adjusting Headers Using Buttons

Having some issues with my JavaScript code. I'm trying to achieve a specific functionality where clicking the "Modify HTML content" button changes the h1 heading from "The Original Content" to "The New Content", and vice versa on subsequent clicks. Si ...

What are the best ways to increase the speed of eslint for projects containing a high volume of files

My git repository contains around 20GB of data, mainly consisting of JSON/CSV/YAML files. Additionally, there are scattered TypeScript/JavaScript (.ts/.js) files among the data files. As the repository has grown in size, I encounter a significant delay eve ...

Tips on filtering an array in a JSON response based on certain conditions in Angular 7

Looking to extract a specific array from a JSON response based on mismatched dataIDs and parentDataIDs using TypeScript in Angular 7. { "data":[ { "dataId":"Atlanta", "parentDataId":"America" }, { "dataId":"Newyork", ...

Create a div element within the parent window of the iFrame

I'm trying to figure out how I can click a button within an iFrame that contains the following code: <td class="id-center"> <div class="bs-example"> <a id="comments" href="comments.php?id=$id" name="commen ...

Typing text into an input field by tapping on a picture

Is there a way to create a feature where users can browse and insert images, which will pull the image URL (all image information is stored in a database) into an input field for submission? Similar to how WordPress allows you to browse, select an image, ...