我如何在jQuery插件中使用数据?

时间:2014-04-05 14:29:28

标签: javascript jquery

例如,有一个简单的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('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);

不太明白,如果我使用数据,我会在每种方法中做一些这样的事情:

            // 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);

这是唯一的方法吗?也许有另一种解决方案?如何在插件方法中使用数据?

1 个答案:

答案 0 :(得分:0)

不,您不必重复此代码。只需在外部作用域中定义data变量,并在任何方法中引用它。它将始终保持您最后加入的价值。

(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);