Multiple Javascript gadgets per page

偶尔善良 提交于 2019-12-11 11:48:14

问题


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?


回答1:


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



回答2:


It looks like you simply need a little OO.



来源:https://stackoverflow.com/questions/1875693/multiple-javascript-gadgets-per-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!