0

Допустим, классическая болванка jQuery-плагина:

(function ($) {
    var defaults = {
        property: 'value'
    },
    methods = {
        init: function (options) {
            return this.each(function() {
                var $this = $(this),
                    data = $this.data('myPlugin');
                if (typeof data === 'undefined') {
                    var settings = $.extend({}, defaults, options);
                    $(this).data('myPlugin', {
                        target: $this,
                        settings: settings
                    });
                }
            });
        },
        destroy: function () {
            return this.each(function () {
                var $this = $(this),
                    data = $this.data('myPlugin');
                $this.removeData('myPlugin');
            })
        },    
        somethingDo: function () {
            // Здесь нужно извлечь данные
            var data = $(this).data('myPlugin');

            // Затем что-то сделать, в результате изменив data
            // ...

            // Затем положить данные обратно
            $(this).data('myPlugin', data);
        }
    };
    $.fn.myPlugin = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        }
        $.error('Метод с именем ' + method + ' не существует для jQuery.myPlugin');
        return this;
    };
})(jQuery);

Не совсем понимаю, если идет работа с данными, то мне в каждом методе плагина придется делать так:

        // Здесь нужно извлечь данные
        var data = $(this).data('myPlugin');

        // Затем что-то сделать, в результате изменив data
        // ...

        // Затем положить данные обратно
        $(this).data('myPlugin', data);

Неужели это единственный путь? Возможно есть другое решение? Ведь это же, считай повтор кода? Как правильно обращаться с данными плагина в его методах?

1 ответ 1

0

https://stackoverflow.com/questions/22882165/how-i-can-use-data-in-jquery-plugin

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.