renderControl: function () {
var that = this;
var _CountryCol = new CountryCol();
var _ComboCol = new ComboCol();
_CountryCol.fetch({
success: function (data) {
that.$("#ctr").select2({
placeholder: "Select a Country",
allowClear: true,
data: JSON.parse(JSON.stringify(data)),
});
}
});
_ComboCol.fetch({
data: { id: 'status' },
success: function (data) {
that.$("#sta").select2({
placeholder: "Select a status",
allowClear: true,
data: JSON.parse(JSON.stringify(data)),
});
}
});
_ComboCol.fetch({
data: { id: 'marital' },
success: function (data) {
that.$("#mrt").select2({
placeholder: "Select a marital",
allowClear: true,
data: JSON.parse(JSON.stringify(data)),
});
}
});
_ComboCol.fetch({
data: { id: 'daytype' },
success: function (data) {
that.$("#dty").select2({
placeholder: "Select a type",
allowClear: true,
data: JSON.parse(JSON.stringify(data)),
});
}
});
this.$("#hpn, #hmn, #icn").numeric({ decimal: false, negative: false });
this.$('#dob').datepicker({
dateFormat: 'dd/mm/yy'
});
},
哪里可以缩短?代码运行良好,只是调用多个ajax看起来麻烦繁琐,代码看起来也不太优雅,如果有人对此有更好的想法,可以分享主干代码的方式,这样更容易管理,谢谢
更新1:
通过参考 Marc 的想法,我进一步减少了代码,但不确定这是否是正确的方法,任何反馈都会很棒
renderControl: function () { //use to render special control
var that = this;
var _CountryCol = new CountryCol();
var _ComboCol = new ComboCol();
$.when(
_CountryCol.fetch(),
_ComboCol.fetch({ data: { id: 'status' } }),
_ComboCol.fetch({ data: { id: 'marital' } }),
_ComboCol.fetch({ data: { id: 'daytype' } })).done(
function (country, status, marital, daytype) {
that.populateSelect('#ctr', "Select a country", country);
that.populateSelect("#sta", "Select a status", status);
that.populateSelect("#mrt", "Select a marital", marital);
that.populateSelect("#dty", "Select a type", daytype);
});
this.$("#hpn, #hmn, #icn").numeric({ decimal: false, negative: false });
this.$('#dob').datepicker({
dateFormat: 'dd/mm/yy'
});
},
populateSelect: function (selector, placeholder, collection) {
debugger;
this.$(selector).select2({
placeholder: placeholder,
allowClear: true,
data: JSON.parse(JSON.stringify(collection[0]))
});
},