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?