Search code examples
javascriptpluginscallbackextend

How to extend javascript library through plugins?


Say i want to develop a library that will keep a very small core and may be extended through plugins.

So i basically came up with something in the scale of:

(function(window){
     window.SomeLibrary =(function(){
          var api = { 
              init: function(){
                  console.log('hi');
                  privateFunction();
                },
              plugin: function(callback) {
                  callback.call();
                }
            };
          var privateFunction = function() {
            console.log('im a private method');
            };
        return api;
        }());
    })(window);

SomeLibrary.init();
SomeLibrary.plugin(function(){
    console.log('im a plugin');
    privateFunction(); //fails;    
});

How can i make the plugin callback executes SomeLibrary private and public methods?

Thanks in advance.


Solution

  • You can collect your private functions in an object and pass this object to the extending plugin.

    Lib.extend('pluginName',function(privates){
        //I have access to privateJob via privates.privateJob();
    });
    

    then in lib:

    var privateCollection = {                 //your private collecting object
        privateJob : function(){...}          //a private function
    }
    
    extend : function(pluginName,callback){ //an extend function that receives callback
        callback(privateCollection);          //execute callback with private collection
    } 
    

    but access to inner functions is a bad idea. this WILL wreck the internals of your library.