Где добавить события на кнопки с машинописью?

0

Где я могу добавить события к кнопкам, полям ввода и т.д.? Я спрашиваю, потому что я хочу удержать как можно больше JS/jQuery от своего представления. Сейчас это то, что я делаю:

У меня есть мое мнение:

@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>

И мой тип машинописного текста

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);
    }    
}

Как вы видите, у меня есть форма, которую я могу отправить нажатием кнопки, но это событие нажатия кнопки должно быть где-то привязано. Если я сделаю это в конструкторе, то мне нужно создать новый класс, как я сделал прямо сейчас. Правильно ли это, или есть ли лучшие способы?

  • 0
    почему вы хотите сделать это в классе. ИМХО, это должно быть сделано после того, как DOMContentLoaded/.ready было DOMContentLoaded/.ready .
Теги:
asp.net-mvc

1 ответ

2
Лучший ответ

Вы можете попробовать что-то вроде этого:

class CurrencyExchangeRateCreate {
    // all the class properties and methods without any event binding.

    private form: JQuery = $("#createForm");
    private submitButton: JQuery = $("#submitButton");

    // a suggestion for the constructor:
    constructor(createUrl, indexUrl) {
      this.createUrl = createUrl;
      this.indexUrl  = indexUrl;
    }

    // some changes in create method:

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

}


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

button.addEventListener('click', function(e){
    e.preventDefault(); // stop the form submission.
    var createUrl = @Url.Action("Create", "Currency"),
        indexUrl  = @Url.Action("Index", "Currency");

    var x         = new CurrencyExchangeRateCreate(createUrl, indexUrl);
        x.Create(); // call the create method here.
});

Ещё вопросы

Сообщество Overcoder
Наверх
Меню