简体   繁体   English

在插件中调用jQuery插件公共函数

[英]Calling jQuery plugin public function within plugin

I know, there are quite a few examples on the Web, but finding real one out of them all is tough for beginner. 我知道,网络上有很多示例,但是对于初学者来说,要从中找出真正的示例是很困难的。 So I want to create jQuery plugin with public methods. 所以我想用公共方法创建jQuery插件。 Example code: 示例代码:

(function($) {
    $.fn.peel = function(options) {
        var defaults = {
        };

        var settings = $.extend({},defaults, options);

        this.public = function() {
            alert("public");
        };

        var private = function() {
            alert("private");
        }

        return this.each(function() {
            //this.public();
            private();
        });
    };
})(jQuery);

As I found, this is the way to make public function, which could be called like this : 正如我发现的那样,这是公开功能的方式,可以这样称呼:

var peel = $('img').peel();
peel.public();

So far it works as expected - public() can be called. 到目前为止,它可以按预期工作-可以调用public()。 But what if i want to call that function within my plugin? 但是,如果我想在插件中调用该函数呢? I commented out in this.each() because it does not work. 我在this.each()中将其注释掉,因为它不起作用。 How can i achieve that? 我该如何实现?

One way to create publicly accessible methods within your plugins is to use the jQuery UI widget factory . 在插件中创建可公开访问的方法的一种方法是使用jQuery UI小部件工厂 This is the framework that jQuery UI uses for all of it's supported UI widgets. 这是jQuery UI用于所有受支持的UI小部件的框架。 A quick example would look like this: 一个简单的示例如下所示:

(function( $ ) {
    $.widget( "something.mywidget", {

    // Set up the widget
    _create: function() {

    },

    publicFunction: function(){
        //...
    }
  });
}( jQuery ) );

var $w = $('#someelement').mywidget();

$w.mywidget('publicFunction');

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

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