How can I extend the public methods in a plugin with jquery?

49 Views Asked by At

How can I extend the public methods in a plugin with jquery?

$.fn.myPluginName = function(PublicOptions) {

    // Remember the root assigned object.
    var Root = this;

    // Set private defaults.
    var Defaults = {
        param1:       'param1',
        param2:       'param2',
        onSuccess:    function(){}
    };

    // Do a deep copy of the options - http://goo.gl/gOSSrg
    var Options = $.extend(true, {}, Defaults, PublicOptions);

    // Private debug function.
    function log(msg) {
        console.debug(msg);
    }

    // Define the public api and its public methods.
    var PublicApi = {

        method1 : function (PublicOptions) {

            return "extended method 1";
        },
        method2 : function (PublicOptions) {

            return "extended method 2";
        }
    };

    // Return the PublicApi object.
    return PublicApi;
};

The extended methods that I want to put them inside var PublicApi = {}

var extensionMethods = {

   method3: function(){
       return "extended method 3";
   },

   method4: function(){
       return "extended method 4";
   }
};

Currently, for console.log($(this).myPluginName());,

Object {method1=function(), method2=function()}

But it would be ideal if I can extend the methods to,

Object {method1=function(), method2=function(), method3=function(), method3=function()}

Is it possible?

1

There are 1 best solutions below

3
Amit Joki On BEST ANSWER

You can just pass the object to the plugin with slight modification of code like

$.fn.myPluginName = function(extMethods){
    //(...) Some code here
    PluginApi = { ... }   // your default methods go here
    if(typeof extMethods == "object"){
       for(var key in extMethods)
           PluginApi[key] = extMethods[key];
    }
}

What if block does is, it checks if the provided argument is an object and then adds the methods to PluginApi by the name of the property using for...in loop.

You can call like $(this).myPluginName(extensionMethods);