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?