使用jQuery插件设计模式调用方法

And*_*w H 11 jquery boilerplate

我一直在使用jQuery Boilerplate来开发插件,而我无法弄清楚的一件事是如何从插件外部调用方法.

作为参考,这里是我正在谈论的样板代码:http: //jqueryboilerplate.com/

在我的小提琴,

http://jsfiddle.net/D9JSQ/2/

这是代码:

;(function ( $, window, document, undefined ) {

    var pluginName = 'test';
    var defaults;

    function Plugin(element, options) {
        this.element = element;

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

        this._name = pluginName;

        this.init();
    }

    Plugin.prototype = {
        init: function() {
            this.hello();
        },
        hello : function() {
            document.write('hello');
        },
        goodbye : function() {
            document.write('goodbye');
        }
    }


    $.fn[pluginName] = function ( options ) {
            return this.each(function () {
                if (!$.data(this, 'plugin_' + pluginName)) {
                    $.data(this, 'plugin_' + pluginName, 
                    new Plugin( this, options ));
                }
            });
    }


})( jQuery, window, document );

$(document).ready(function() {
    $("#foo").test();
    $("#foo").test('goodbye');
});
Run Code Online (Sandbox Code Playgroud)

我试图使用以下语法调用goodbye方法:

$("#foo").test('goodbye')
Run Code Online (Sandbox Code Playgroud)

我该如何实现这一目标?提前致谢

use*_*654 19

您必须获得对该类的引用,以使用该插件结构调用它的方法.

http://jsfiddle.net/D9JSQ/3/

$(document).ready(function() {
    var test = $("#foo").test().data("plugin_test");
    test.goodbye();
});
Run Code Online (Sandbox Code Playgroud)

要做你想做的事,你必须摆脱document.write来测试它.

http://jsfiddle.net/D9JSQ/8/

;
(function($, window, document, undefined) {

    var pluginName = 'test';
    var defaults;

    function Plugin(element, options) {
        this.element = element;

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

        this._name = pluginName;

        this.init();
    }

    Plugin.prototype = {
        init: function(name) {
            this.hello();
        },
        hello: function(name) {
            console.log('hello');
        },
        goodbye: function(name) {
            console.log('goodbye');
        }
    }


    $.fn[pluginName] = function(options) {
        return this.each(function() {
            if (!$.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName, new Plugin(this, options));
            }
            else if ($.isFunction(Plugin.prototype[options])) {
                $.data(this, 'plugin_' + pluginName)[options]();
            }
        });
    }


})(jQuery, window, document);

$(document).ready(function() {
    $("#foo").test();
    $("#foo").test('goodbye');
});?
Run Code Online (Sandbox Code Playgroud)

查看控制台以获取信息.

  • 参数可以使用此方法传递吗? (2认同)