每页多个 Javascript 小工具
我正在用 Javascript 和 jQuery 编写一个内部小工具。我以面向对象的方式编写了它,其中有一个名为 ggObj 的顶级对象,并通过 ggObj.prototype 分配了方法。
要使用我的小工具,您需要包含 myGadget.js 文件并在页面中调用函数 makeMyGadget()。我的 JS 文件如下所示:
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();
}
到目前为止,它运行良好。
我的问题是这个小工具没有像我希望的那样封装。按照目前的情况,每页只能有一个小工具 (myGG)。更糟糕的是,在我的代码中,我必须引用特定的对象实例 (myGG)。其中两个示例是:
myShinyRedButton 的 onClick 执行“myGG.submitForm()”,
执行“动画”,我有以下代码行:
this.intervalID = setInterval( "myGG.pageData(1)", this.options.animate );
我需要更改什么才能正确封装我的代码,以便页面上可以存在多个小工具?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能想看看创建一个 jQuery 插件。
然后,您可以将 MYPLUGINNAME 添加到页面上的任何元素。
因此,要执行动画等操作,您现在可以使用内置的 jQueryAnimation() 函数。
有一些在线教程可以提供帮助。像这样:
You probably want to look at creating a jQuery plugin.
You can then add MYPLUGINNAME to any element on the page.
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:
看起来你只需要一个 小 OO< /a>.
It looks like you simply need a little OO.