简体   繁体   中英

How i can use data in jQuery plugin?

For example, there is a simple jQuery plugin template

(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('photoBoard', {
                        target: $this,
                        settings: settings
                    });
                }
            });
        },
        destroy: function () {
            return this.each(function () {
                var $this = $(this),
                    data = $this.data('myPlugin');
                $this.removeData('myPlugin');
            })
        },

        somethingDo: function () {
            // here i need get data
            var data = $(this).data('myPlugin');

            // something do with data
            // ...

            // and at the end put data back
            $(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);

Do not quite understand, if i use the data, i have will in each method do something like this:

            // here i need get data
            var data = $(this).data('myPlugin');

            // something do with data
            // ...

            // and at the end put data back
            $(this).data('myPlugin', data);

Is this the only way? Perhaps there is another solution? How to use data in plugin methods?

No, you don't have to repeat this code. Just define data variable in the outer scope and refer to it in any methods. It will always hold the value you last put into it.

(function ($) {
    var defaults = {
        property: 'value'
    },
    data,
    methods = {
        somethingDo: function () {
            // only needed if it wasn't set by methods called previously
            // data = $(this).data('myPlugin');

            // something do with data
            // ...

            // and at the end put data back
            // you could move this call to a helper function as well
            $(this).data('myPlugin', data);
        }
    };
})(jQuery);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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