The jQuery documentation suggests storing additional information for DOMElement using data () . But it's hard for me to access the stored data in a good way.
The area changes when I call other functions, because of which I lose my path :)
(function ($) { var methods = { init: function (options) { return this.each(function () { var $this = $(this), data = $this.data('myPlugin'); if (!data) { $(this).data('myPlugin', { testValue: true }); data = $this.data('myPlugin'); } }); }, testFunction: function () { console.log('t: '+$(this).data('myPlugin').testValue); methods.otherFunction(); }, otherFunction: function () { console.log('o: '+$(this).data('myPlugin').testValue); } }; $.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); } else { $.error('Method ' + method + ' does not exist on jQuery.myPlugin'); } }; })(jQuery); $(document).ready(function () { $('body').myPlugin(); $('body').myPlugin('testFunction'); });
Console output:
t: true Uncaught TypeError: Cannot read property 'testValue' of undefined
source share