Alec Smart
Alec Smart

Reputation: 95900

Extend a jQuery plugin

Say I have a jQuery plugin like $.abc = function() {}. Now I want to provide an extra module which uses the same scope as $.abc and extends its functionality. For e.g. in my abc plugin I will check if say a variable mod1 = true; if its true, then I will automatically call thoso functions of mod1.

My question is how do I write mod1 so that it can share the same namespace as my base plugin and I am able to call it from my plugin e.g. mod1.getFiles();

Thankyou for your time. Sorry if this is not very clear. I will explain again if you have any questions.

UPDATE: How do I call function test of pluginbar?

$.fn.pluginFoo = function() {
    ...
     CALL FUNCTION TEST OF PLUGINBAR
    ...
};

$.fn.pluginBar = function() {
    ...
    function test() {
        alert('this is a test'); 
    }
    ...
};

Upvotes: 2

Views: 6668

Answers (2)

RaYell
RaYell

Reputation: 70414

There is no need to create a shared data object. You can expose some functionality of one plugin to other plugins using simply return statement.

$.fn.pluginFoo = function () {
     // here you can access public "members" of pluginBar
     $.fn.pluginBar.fn3();
     $.fn.pluginBar.fn4();
}


$.fn.pluginBar = function () {
    // private "members" (only this plugin can access them)
    var fn1 = function () { ... }
    var fn2 = function () { ... }

    // public "members" (other plugin can access that as well)
    // fn3 is defined in the return, fn4 allows to access private function fn1
    return {
        fn3: function () { ... },
        fn4: fn1
    };
}

Upvotes: 2

dyve
dyve

Reputation: 6013

You want two plugins to access a shared set of data / functions, you could do it like this:

var myPluginData = {
    flag: true,
    alertNothing: function() {
        alert('I do Nothing');
    }
};

$.fn.pluginFoo = function() {
    ...
    myPluginData.flag = false;
    myPluginData.alertNothing();
    ...
};

$.fn.pluginBar = function() {
    ...
    myPluginData.alertNothing();
    myPluginData.flag = true;
    ...
};

You don't actually need to define an object for it, but it does make things clearer.

Upvotes: 0

Related Questions