Posts  >  Adding a namespace to jQuery extension functions

Adding a namespace to jQuery extension functions

The javascript library jQuery has the ability to extend functions, which allows you to create your own jQuery functions. To prevent your custom functions from having conflicting names it is a good idea to put them in their own namespace. One method of doing so is to create an object and put the functions in the object so they can be called like:

  $(yourSelector).yourNamespace.function()
I first tried to implement this idea but ran into the issue of not being able to access $(this)of the parent $(this).yourNamespace in the function itself since "this" has a different context in a function.

My resolution to this was to create one function that takes in a callback name that is called by that function. The different functions are stilled stored in an object, but since they are called by the function the correct context of $(this) can be used.

An example of calling a function using this approach would look like:

$(yourSelector).yourNamespace("function"); // where function is the name of a callback function in .namespace()

A callback function can be added to $(yourSelector).yourNamespace(); by adding to the callbacks object similar to below:

  // example callback function 
  callbacks.yourFunction = function (params) {
    if (params.length != 2) {
        return { msg : "invalid params", numParams : 1 }; // second param is default and always set 
   }
   var yourParam = params[0];
   var jquery = params[1];
   // do something with params 
   // example jquery html function call on $(this) of yourNamespace
   jquery.html("<div>" + yourParam + "</div>")
   return  { msg : "OK" };
  }

  // can be called like 
  $(".selector").yourNamespace("yourFunction", [ yourParam ]);

In the github at the end of the post there is another example that also shows how error logging works and some additional callback functions. If invalid parameters or an unknown callback function name are passed an error message is logged to the console using the logger object.

Github Repository

Comments