3

I have been creating my own library for a custom layout script. For ease of use, I am trying to emulate how jQuery exposes its library through the jQuery() which makes the code very easy to read and straightforward. I have come up with something that works but I am not sure if this is the correct way to do this. Rather than keep the functions internal all the functions are "appended" to the library. Anyways, the code which works for me so far is as follows:

slateUI = (function(slateID){
    slateUI.ID = slateID;
    return slateUI;
});

and a related function looks something like this:

slateUI.doSomething = function(content)
{
    //DID SOMETHING USING slateUI.ID
}

I am fairly new to OOP like features of the language. I am sure there is a better way to approach this. The issue that I have is handing down the Element to an appened function call so for instance:

slateUI("#someSlate").doSomething(...)

Obtains its element from the slateUI.ID

Is this the correct way to approach this? Or is this a hacked way that I came up with and there is some straight forward way to do this?

Joakim Johansson
  • 3,196
  • 1
  • 27
  • 43
Serguei Fedorov
  • 7,763
  • 9
  • 63
  • 94

2 Answers2

1
// function which returns a new SlateUI object (so we dont have to use the "new" keyword)
slateUI = function ( slateID ) {
    return new SlateUI( slateID );
};

// class definition
function SlateUI ( slateId ) {
    this.id = slateId;
}
// methods added to the class prototype (allows for prototypical inheritance)
SlateUI.prototype.someFunction = function() {
    alert( this.id );
    return this; // adding this line to the end of each method allows for method chaining
};

// usage
slateUI( 'someid' ).someFunction();
dqhendricks
  • 19,030
  • 11
  • 50
  • 83
  • Answet is very good but jquery returns the Array Has the Elements in each chain please tell me how to do that Urgent – Marwan Dec 11 '12 at 14:42
0

The short version of your question is that you're looking for the ability to chain your functions.

This is achieved simply by returning the relevant object from each function. If the function has no other return value, then just return the this variable, to pass control back to the caller.

Spudley
  • 166,037
  • 39
  • 233
  • 307