Multiple Javascript gadgets per page
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:
the onClick for myShinyRedButton executes 'myGG.submitForm()', and
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?
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:
- Creating a plugin
- Another tutorial
It looks like you simply need a little OO.
精彩评论