我在哪里向按钮,输入字段等添加事件?我问是因为我想尽可能多地保留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);
}
}
就像您看到的那样,我有一个可以单击按钮提交的表单,但是此按钮单击事件必须绑定在某处。如果在构造函数中执行此操作,则必须像现在一样实例化新类。是这样做的正确方法,还是有更好的方法?
您可以尝试如下操作:
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.
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句