Подтвердить что ты не робот

Вызов методов с использованием шаблона проектирования JQuery Plugin

Я использую 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');
});

Я пытаюсь вызвать метод goodbye, используя следующий синтаксис:

$("#foo").test('goodbye')

Как мне это достичь? Спасибо заранее

4b9b3361

Ответ 1

Вам нужно будет получить ссылку на класс, чтобы вызвать его метод с этой структурой плагина.

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

$(document).ready(function() {
    var test = $("#foo").test().data("plugin_test");
    test.goodbye();
});

Чтобы сделать то, что вы хотите, вы должны избавиться от 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');
});​

Посмотрите на консоль для информации.