これは、よく構築されたjQueryプラグインテンプレートです。 これは、明確に改善されたわずかに改訂されたバージョンと、ベストプラクティスのためのいくつかのマイナーな調整を備えています。
キーテイクアウェイ この記事では、カスタムjQueryプラグインを構築するための基盤として機能する堅牢なjQueryプラグインテンプレートを紹介します。これは、プラグインの定義、デフォルトのオプション設定、オプションの更新、イベント処理、および状態管理を包括的にカバーしています。 このテンプレートは、基本的なプラグインの作成、オプション統合、チェーン性、プライベート/パブリックメソッドの実装、イベント処理、要素アクセス、状態保存、プラグインの破壊を示す実用的な例を提供します。 チェーン可能性のためにjQueryオブジェクトを返すことと、国家管理のためのjQueryの
方法を利用することの重要性が強調されています。このテンプレートは、次のjQueryプラグインの開発に最適な出発点です。 作業例は、https://www.php.cn/link/a598e7d200bf02558d5534839884b7a3data()
。にあります
/*! jQuery [name] plugin @name jquery.[name].js @author [author name] ([author email] or @[author twitter]) @version 1.0 @date 01/01/2013 @category jQuery Plugin @copyright (c) 2013 [company/person name] ([company/person website]) @license Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license. */ (function($) { // Default plugin options const defaultOptions = { myVar1: 1, myVar2: 2, myVar3: 3, resizeDelay: 50, // etc... }; // Plugin constructor function MyPlugin(element, options) { this.element = element; this.settings = $.extend({}, defaultOptions, options); this.resizeTimer = null; this.init(); } // Plugin methods MyPlugin.prototype = { init: function() { // Initialization logic here... if (this.settings.autoResize) { $(window).on('resize.myPlugin', this.onResize.bind(this)); } }, update: function(options) { $.extend(this.settings, options); }, onResize: function() { clearTimeout(this.resizeTimer); this.resizeTimer = setTimeout(this.resizeFunc.bind(this), this.settings.resizeDelay); }, resizeFunc: function() { // Resize handling logic here... }, destroy: function() { clearTimeout(this.resizeTimer); $(window).off('resize.myPlugin'); $(this.element).removeData('myPlugin'); // Remove plugin data } }; // jQuery plugin method $.fn.myPlugin = function(options) { return this.each(function() { const $this = $(this); let plugin = $this.data('myPlugin'); if (!plugin) { plugin = new MyPlugin(this, options); $this.data('myPlugin', plugin); } else if (typeof options === 'string' && plugin[options]) { //Call a method on the plugin plugin[options](); } else if (options) { plugin.update(options); } //Ensure chainability return this; }); }; }(jQuery));
const
let
コンストラクターパターン:MyPlugin
forbind()
メソッドチェーン:this
チェーン性を維持するためにを明らかに戻します
this
this
removeData()
)の呼び出しを許可します
removeData()
destroy
より明確なコメント:.myPlugin('destroy')
以上が優れたjQueryプラグインテンプレートの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。