farina
farina

Reputation: 3566

Create JQuery like plugin structure in custom javascript

I DO NOT WANT TO CREATE A JQUERY PLUGIN

Let's say I have something like this:

// In folib.js
function Foo() {this.Prop = function() {//do something}};

So my users can reference my JavaScript library and instantiate my object all day

// In consumer
foo = new Foo();
alert(foo.Prop);

Now, I want to create a JQuery like plugin system for my class, whereas I can create plugin script libraries which extend Foo().

I think I should be doing something like this...

(function( foo ){
    foo.myPlugin = function() {  
       // Do your awesome plugin stuff here
    };
})(Foo);

But I can't get that working. Any ideas on how this is done in JQuery? I can't figure it out :(

Upvotes: 1

Views: 1739

Answers (2)

David Tang
David Tang

Reputation: 93684

Using prototype:

Foo.prototype.myPlugin = function () { /* Do plugin stuff */ };

Then you will be able to access the plugin like so:

var foo = new Foo();
alert(foo.myPlugin);

Prototypes work when used in conjunction with new: the new object (foo) has a hidden pointer to the prototype object of the function it was constructed from (Foo). If a property isn't found on the new object, JS will search for it in the prototype. For more information, read this.

jQuery does a similar thing by providing a fn property which points to prototype:

Foo.fn = Foo.prototype;

Upvotes: 5

smdrager
smdrager

Reputation: 7417

To follow up on Box9's great answer, you should also return the object on which you are performing the action.

Foo.prototype.myPlugin = function () { 
     /* Do plugin stuff */ 

     return this; //return the object's instance
};

This will enable you to chain functions modifying the same object. This is part of what makes jQuery so popular--it uses a fluent interface which allows for more expressive syntax when chaining functions and plugins. http://en.wikipedia.org/wiki/Fluent_interface

This maybe not be what you were asking for, but it is particularly helpful when creating many functions extending an object.

myFooInstance.DoSomething(5).DoAnotherThing('hello').YetAnother();

Upvotes: 3

Related Questions