Sprose
Sprose

Reputation: 1345

Wrap a function from a JavaScript library for use in my own JavaScript library

So I am trying to build a JavaScript library. I do not want to write all my functions from scratch, most of the functions I want to use are already available in other libraries, the point of my library is to group these together into my own library to make things easier for continuous use.

I am looking for an example of how to wrap functions from other JavaScript libraries so I can use them within my own.

The way I had thought it would work was I would reference the libraries in which the functions are being taken for at the top of my code

I would then have

function NameOfFunction(){
*wrapped function from referenced library*
}

for each function

Upvotes: 0

Views: 1132

Answers (2)

Jérémy Dutheil
Jérémy Dutheil

Reputation: 6137

You can use oriented-object Javascript, that will allow you to wrap functions from other libraries ; still, be conscious that the external librairies need to be there, or you wouldn't be able to use their functions. ;)

Imagine this kind of code :

var myObject = {};

myObject.myMethod = function( param1, param2 ) {

};

Then you just have to call myObject.myMethod( param, param ), 'cause myObject will be used like an object. We can easily imagine that you wrap libraries functions inside this kind of method, or even simply return a call to another library function.

Does that answer to your question ?

EDIT : and if you really want an oriented-object style, you can do like this

function myObject() {
    this.myMethod = function( param1, param2 ) {
        return externalLib.myMethod();
    }
}

var objInstance = new myObject();
var something = myObject.myMethod();

Upvotes: 1

Shreyas
Shreyas

Reputation: 1462

If your library exposes functions in an object, like underscore or any other utility libraries, then you can use _.extend or jquery extend to copy all of them into a single object.

var myLib = {};
_.extend(myLib,helperLib1,helperLib2,...)

Upvotes: 0

Related Questions