Search code examples
javascriptphpjqueryclassapi-design

JavaScript Period Functionality: How do I setup a library like jQuery did


Intro# (Edited)

Hey everyone, I'm setting up a JavaScript library that is designed to us AJAX and connect to a number of PHP, which then connects to the database. (fairly certain that this is what you call an API). To make things easier for my team, though, I wanted to setup some sort of initialization object like the $ in jQuery. Can someone help point me to the right data type?

Example

// Pull new user data from fields
var username = $.("#usernamefield").val();
var password = $.("#userpassfield").val();

// Send data to library through
API.AddUser(username, password);

// Sorry for any syntax errors, this is just example code

Potential Solution

I did consider using a class system, but I did some research, and it seems like there may be a better way. Can someone help explain how jQuery setup their library?

Clarificaton

A few people asked why I don't just use jQuery. Well, actually, I am. I'm using jQuery and building this separate library for uploading information with PHP. They two are Apples and Oranges, but I do want to have an initializer like jQueries "$" - Can somebody explain how they did it?


Solution

  • Here is how you should do it:

    In a JS template that you could call API.js, you will have the following:

     ;(function($){
    
        /* ========================================================
        /* Global variables */
        /* =======================================================*/
        var api = null;
    
       /* ========================================================
        /* Ajax calls */
        /* =======================================================*/
    
        var API = function(args)
        {
            // Api methods 
    
            this.AddUser = function (username, password)
            {
    
                //To do Ajax call
            }
    
            this.DeleteUser = function(id)
            {
                //To do Ajax call
            }
    
            // ... More api methods
        };
    
       /* ========================================================
        /* Main function */
        /* =======================================================*/
    
        jQuery.fn.API = function( args )
        {
            api = new API(args);
            return api;
        };
    
    
    })(jQuery);
    

    Then when you need to make an Ajax call, you just need to initialise an API object with any required arguments as follows:

    $(function() {
         //Note: you can pass global arguments.
        var API = $().API();
    
        //You can then make your api calls with required values
    
        // Pull new user data from fields
        var username = $("#usernamefield").val();
        var password = $("#userpassfield").val();
    
        // Send data to library through
        API.AddUser(username, password);
    
    });