0
\$\begingroup\$

I am creating a few functions that wrap around jQuery's Ajax function to make it a bit quicker and easier to perform a request. For this I have this JavaScript file:

$( document ).ready( function ()
{
    var ajax = {
        url: "", type: "", success: "", beforeSend: "",
        preform: function ( $url, $type, $success, $beforeSend )
        {
            $.ajax( {
                url: this.url = $url,
                type: this.type = $type,
                success: setSuccess(this.success = $success),
                beforeSend: setBeforeSend(this.beforeSend = $beforeSend)
            } );
        }
    };

    function setSuccess( $selector )
    {
        return function ( $r )
        {
            $( $selector ).html( $r );
        };
    }

    function setBeforeSend( $selector )
    {
        return function ()
        {
            $( $selector ).html( "Loading..." );
        };
    }
} );

And this is used with the following line of code:

ajax.preform( "script/javascript/ajaxfiles/print.php", "GET", "#success", "#before" );

This is working brilliantly, but is there a better way to do this?

\$\endgroup\$

1 Answer 1

5
\$\begingroup\$

I heard you like wrappers

So I wrapped your wrapper (jQuery) in a wrapper (your thing) so you can do ajax.

Why do you do this again??

Instead of wrapping over (slow) jQuery you could just wrap the native ajax functionality. In general I expect that to be faster. Additionally this frees your API to be changed independently of jQuery and it removes that nasty jQuery dependency at all.

Don't wrap wrappers in wrappers, unless you add significant functionality

What significant improvement does your API provide over jQuery's?

\$\endgroup\$
1
  • \$\begingroup\$ The purpose of this is simply to make is easier and faster (in regards to typing time) to make an ajax request, it doesn't allow anything more than this other than it stores the last request data so you can run it again or check it \$\endgroup\$
    – anon
    Commented Feb 1, 2016 at 12:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.