Skip to content

Instantly share code, notes, and snippets.

@milmazz
Last active Aug 29, 2015
Embed
What would you like to do?
DRY principle
// Before:
// CallBacks.loadJsonView(url, "POST", Historicals.UpdateCombo, params);
// After:
$.post(url, params, Historicals.UpdateCombo, "json");
// Before:
// CallBacks.loadPartialView(url, "POST", infoDialog, params);
// After:
$.post(url, params, infoDialog, "html");
var CallBacks = (function ($) {
var baseLoadView = function (cadurl, method, fn, datatype, params) {
var ajaxOptions = {
url: cadurl,
dataType: datatype,
contentType: "application/json",
cache: false,
type: method,
success: function (data) {
fn(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
var strmsg = "Status: " + textStatus + ". Error: " + errorThrown;
alert(strmsg);
}
};
if (typeof params !== "undefined") {
$.extend(ajaxOptions, {
data: JSON.stringify(params),
success: function (data) {
fn(data, params);
}
});
}
$.ajax(ajaxOptions);
};
return {
loadJsonView: function (cadurl, method, fn, params) {
baseLoadView(cadurl, method, fn, "json", params);
},
loadPartialView: function (cadurl, method, fn, params) {
baseLoadView(cadurl, method, fn, "html", params);
},
loadPartialViewWithoutParams: function (cadurl, method, fn) {
baseLoadView(cadurl, method, fn, "html");
},
loadJsonViewWithoutParams: function (cadurl, method, fn) {
baseLoadView(cadurl, method, fn, "json");
}
};
}(window.jQuery));
var CallBacks = new function () {
this.loadJsonView = function (cadurl, method, fn, params) {
$.ajax({
url: cadurl,
data: JSON.stringify(params),
dataType: 'json',
contentType: 'application/json',
cache: false,
type: method,
success: function (data) {
fn(data, params);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
var strmsg = "Status: " + textStatus + ". Error: " + errorThrown;
alert(strmsg);
}
});
};
this.loadPartialView = function (cadurl, method, fn, params) {
$.ajax({
url: cadurl,
data: JSON.stringify(params),
dataType: 'html',
contentType: 'application/json',
cache: false,
type: method,
success: function (data) {
fn(data, params);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
var strmsg = "Status: " + textStatus + ". Error: " + errorThrown;
alert(strmsg);
}
});
};
// And so on, you get the idea.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment