views:

61

answers:

2

I'm writing an in-house gadget in Javascript and jQuery. I've written it in an object-oriented manner with a top-level object called, as an example ggObj and assigned methods via ggObj.prototype.

To use my gadget, you include the myGadget.js file and you call the function makeMyGadget() in your page. My JS file looks like this:

var myGG ; 

function ggObj = {  // lots of stuff here }
ggObj.prototype = { // more stuff here }

var makeMyGadget = function() {

   myGG = new ggObj();
   myGG.initialize(); 
   myGG.print(); // write HTML for my gadget to the 
                 // browser, a la a HERE DOC
   myGG.doOtherFancyStuff();
}

so far, it works well.

My problem is the gadget is not as encapsulated as I'd like it to be. As it stands now, you can only have one gadget (myGG) per page. To make matters worse, within my code, I've had to refer to the specific object instance (myGG). Two examples of that are:

  1. the onClick for myShinyRedButton executes 'myGG.submitForm()', and

  2. to do "animation", I have the following line of code:

    this.intervalID = setInterval( "myGG.pageData(1)", this.options.animate );

What do I need to change to properly encapsuslate my code so multiple gadgets can exist on a page?

+3  A: 

You probably want to look at creating a jQuery plugin.

$.fn.MYPLUGINNAME = function() {
  return this.each(function() {
  //your code to manipulate the element here
  //you can use this to refer to a specific instance of an element
  //if you apply the plugin to multiple elements on the page.
 });
}

You can then add MYPLUGINNAME to any element on the page.

 $('a').MYPLUGINNAME();

So to do animation etc you can now use the built in jQuery animation() functions.

There are several tutorials online that could help. Like this:

Vincent Ramdhanie
I was hoping for a native JS (non-jQuery) approach, but I'll give it a shot. Thanks for the idea.My "animation" is paging through a list so jQuery's animate() won't help with that.
A: 

It looks like you simply need a little OO.

Upper Stage