Warning: Use of undefined constant id - assumed 'id' (this will throw an Error in a future version of PHP) in /kunden/247608_14469/webseiten/wp-content/themes/wordblab/functions.php on line 28
Warning: Use of undefined constant text - assumed 'text' (this will throw an Error in a future version of PHP) in /kunden/247608_14469/webseiten/wp-content/themes/wordblab/functions.php on line 29
Warning: Use of undefined constant text - assumed 'text' (this will throw an Error in a future version of PHP) in /kunden/247608_14469/webseiten/wp-content/themes/wordblab/functions.php on line 9
In „Eigenes jQuery-Plugin selbst schreiben“ habe ich gezeigt, wie man ganz einfach ein eigenes jQuery Plugin schreiben kann. Aus Speicherplatzgründen empfiehlt es sich aber Plugins, die mehrfach instanziiert werden, mit einem Prototypen anzulegen. Wie das funktioniert, soll folgender Code exemplarisch zeigen.
Das jQuery-Plugin „myWidget
“ gibt im Sekundentakt die ID des Elements aus, auf dem es angewandt wurde. Im data
-Attribut des Elements wird eine Instanz zum Plugin gehalten, über die das Plugin dann auch wieder gestoppt werden kann (mit der destroy
-Methode).
Plugin
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | function MyWidget(element, options) { this.$element = $(element); this.options = options; this.init(); } MyWidget.prototype.init = function() { var self = this; this.intervalID = window.setInterval(function() { console.log(self.$element.attr('id')); }, 1000); this.$element.data('my-widget-instance', this); }; MyWidget.prototype.destroy = function() { window.clearInterval(this.intervalID); }; $.fn.myWidget = function(options) { return this.each(function() { new MyWidget(this, options); }); }; |
Aufruf
var element = jQuery('#tilePreview').myWidget(); element.data('my-widget-instance').destroy(); |