views:

82

answers:

1

Let's start by saying that my code works perfectly fine, there is no problem with it. I just want to wrap it all up with a nice class for dynamic future use, and I wonder how to do that in Javascript in the most correct way.

load_server is a function that puts an Ajax request. pagination() / itemlinks() are functions that go through the retrieved data and marks links for future Ajax use. I currently write everything in functions and just dump it in the code, but I would like to create something like:

function ajaxRequest(type, link, container) {
    this.after_success = null;
    this.check_pagination = true;
    if(typeof(type)) == ‘undefined’) this.type='';
    if(typeof(link)) == ‘undefined’) this.link='';
    if(typeof(container)) == ‘undefined’) this.container='';

    this.pagination=function() {
        //static function..
    };
    this.load_server=function () { 
        //function logic here..
    };
    while(mainReq.after_success) {
        func();
    }
}

var mainReq = new ajaxRequest{'link'};
mainReq.after_success = {
    itemlinks = function() { },
    morefunc = function() { }
};
mainReq.submit();

I currently use the following jQuery code:

load_server = function (type, link, container) {
$(container).html("<div class='mask-loading'>Loading ...</div>");

$(container).load(getUrl, 
function(responseText, textStatus, XMLHttpRequest) { //Callback function.
    if(textStatus=='success') {
        pagination_render();
        itemlinks();
    }
    else {
        $(container).html("We are sorry, but there was an error with your request.<br />Please try again.");
    }
});
}
var pagination_render = function() {
    var pagination = $('.pagination a');
    pagination.each(function() {
        $(this).click(function(event) {
            console.log(this.href);
            load_server('page', this.href, '#tab1');
            return false;
        });
    });
};
pagination_render(); //init any pagination files

The other functions are the same, so no need to splash them around..

+4  A: 

If you want classes and inheritance in Javascript, have a look at Mootools or John Resig's blog.

Note: both are (heavily) inspired by Dean Edward's Base.js.

Gregory Pakosz