I've been working on a new project and I've found myself needing to make multiple Ajax calls, often on the same page and at the same time. I decided rather than repeating code that I would try and make a reusable object that to handle these calls.
I'm very new to Object Orientated JavaScript so I'm looking for some feedback and advice on my code; am I doing it right? is there something I'm not doing? should I be doing things differently etc?
Here's my Ajax constructor:
/**
*
* AjaxRequest Constructor
*
* @param url
* @param success_callback
* @param limit
* @param type
* @constructor
*/
function AjaxRequest (url, success_callback, limit, type) {
this.url = url;
this.success_callback = success_callback;
this.limit = limit || 3;
this.type = type || "POST";
//init ajax
this.init();
}
/**
* initialise
* ajax
*/
AjaxRequest.prototype.init = function () {
var _self = this;
$.ajax({
dataType: "json",
url: this.url,
type: this.type,
data: {
member_id: 1,
limit: this.limit
},
beforeSend : function (){
console.log('loading');
//spinner.spin(target);
},
success: function (response) {
if (response.success === 1) {
_self.success_callback(response);
}
},
error: function (a, b, c) {
}
});
}
/**
* change number of
* displayed outputs
* @param limit
*/
AjaxRequest.prototype.set_limit = function (limit) {
this.limit = limit;
this.init();
}
and here is how I'm calling it
/**
* instantiate getAchievements
* @type {AjaxRequest}
*/
getAchievements = new AjaxRequest("/ajax-member/get-achievements", function (response) {
var i,
container = document.getElementsByClassName('achievements-container')[0],
achievements_data = '';
for (i in response.achievements) {
achievements_data += ("<div class='achievement'><div class='copy'><h2>" + response.achievements[i].t_achievement_name + "</h2><span>" + response.achievements[i].t_achievement_description + "</span></div></div>");
}
container.innerHTML = achievements_data;
});
/**
* instantiate getComments
* @type {AjaxRequest}
*/
getComments = new AjaxRequest("/ajax-member/get-comments", function (response) {
var i,
container = document.getElementsByClassName('comments')[0],
comments_data = '';
for (i in response.comments) {
comments_data += ("<div class='comment'><div class='copy'><h2>" + response.comments[i].t_fname + " " + response.comments[i].t_lname + "</h2><span>" + response.comments[i].t_comment_content + "</span></div></div>");
}
container.innerHTML = comments_data;
});
It would be good to hear some feedback on this. I'm always looking to improve and find the best ways of doing things so if you spot something I should be doing differently then please shout.