简体   繁体   English

编写一个jQuery插件:公共方法和多个插件实例

[英]Write a jQuery plugin: public methods and multiple plugin instances

I've been working for hours on writing jQuery plugin, read the documentation, searched through posts and so on. 我已经花了几个小时编写jQuery插件,阅读了文档,在帖子中进行了搜索等等。 One thing is not clear yet. 一件事还不清楚。 I'm writing a plugin with multiple instances, so I've got something like this 我正在编写具有多个实例的插件,所以我有类似的东西

<div id="box1" class="box"></div>
<div id="box2" class="box"></div>

<script type="text/javascript">
    $(".box").myPlugin();
</script>

So the plugin will act on two DOM elements. 因此,该插件将作用于两个DOM元素。 Here is a plugin demo. 这是一个插件演示。 Let's say that I need one or more private variables (myValue in the demo), of course any instance (box1, box2) has got different values. 假设我需要一个或多个私有变量(演示中为myValue),当然任何实例(box1,box2)的值都不同。

(function ( $ ) {

    $.fn.myPlugin = function() {

        this.each(function() {

            /* this is a private variable */
            var myValue = Math.floor(Math.random() * 10000);
        });  

        return this;
    };

    /* this is a public method */
    $.fn.myPlugin.showValue = function() {
        alert('My value is ' + myValue);
    };

}( jQuery ));

Now I need this plugin to expose one public method to read/write such private variable. 现在,我需要这个插件来公开一个公共方法来读取/写入此类私有变量。 The code above will fail with "myValue is undefined" error, of course. 当然,上面的代码将失败,并显示“ myValue is undefined”错误。

I need, in some way, to get a reference to any instance, and then to call 'their' public method. 我需要以某种方式获取对任何实例的引用,然后调用“其”公共方法。 Something like 就像是

$('#box2').showValue() /* ??? $('#box2')。showValue()/ * ??? */ * /

Any help will be appreciate. 任何帮助将不胜感激。 Thank you. 谢谢。

Unfortunately there's no easy way to make your example work without simply defining additional "plugins" on the $.fn namespace . 不幸的是,如果不简单地在$.fn namespace上定义其他“插件”,就没有简单的方法来使示例工作。

Normally, methods of a plugin are implemented either as arguments passed to the plugin: 通常,插件的方法可以作为传递给插件的参数来实现:

$("foo").myPlugin(); // initialize
$("foo").myPlugin("doSomething"); // do something

or by having an "instance" object available: 或通过提供“实例”对象来实现:

$("foo").myPlugin(); // initialize
var inst = $("foo").data("myPlugin"); // get instance
inst.doSomething(); // do something

An example of the first option can be found here: http://learn.jquery.com/plugins/basic-plugin-creation/ 可以在这里找到第一个选项的示例: http : //learn.jquery.com/plugins/basic-plugin-creation/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM