亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
1 - You are not making a jQuery plugin
2 - You are not (correctly) documenting your code
3 - You are not providing enough flexibility or customizability
4 - 您需要太多配置
5 - 您正在混合外部 CSS 規(guī)則和內(nèi)聯(lián) CSS 規(guī)則
6 - 你沒有提供示例
7 - 你的代碼與他們的 jQuery 版本不匹配
8 - 變更日志在哪里?
其他資源
9 - 沒有人需要你的插件
10 - 您沒有提供縮小版本
11 - 你的代碼太聰明了
13 - 您沒有自動化該過程
Несколько полезных ресурсов
Заключение
Home CMS Tutorial WordPress 14 Possible Explanations Why Your jQuery Plugin Is Not Used

14 Possible Explanations Why Your jQuery Plugin Is Not Used

Sep 04, 2023 pm 03:05 PM

jQuery 插件未使用的 14 種可能解釋

With so many people developing jQuery plugins, it's not uncommon to encounter a situation where one simply - for lack of a better language - sucks. There are no examples or documentation, the plugin does not follow best practices, etc. But you are one of the lucky ones: this article details the pitfalls you must avoid.

For those who often use Nettuts, jQuery is no stranger. Jeffrey Way's 30 Days to Learn jQuery (and various other tutorials here and elsewhere) are great and lead us all down the road to Sizzle-powered Awesomesauce. Amid all the hype (and the giant leap in JavaScript adoption by developers and browser vendors), a plethora of plugins have emerged. This is part of the reason why jQuery is the most popular JavaScript library! The only problem is that many of them aren't very good.

In this article, we will focus less on JavaScript specifically and more on best practices for plugin delivery.


1 - You are not making a jQuery plugin

There are a few patterns that are more or less universally accepted as the "right way" to create jQuery plugins. If you don't follow these conventions, your plugin might... suck! Consider one of the most common patterns:

(function($, window, undefined){
$.fn.myPlugin = function(opts) {
	var defaults = {
		// setting your default values for options
	}

  // extend the options from defaults with user's options
  var options = $.extend(defaults, opts || {});

	return this.each(function(){ // jQuery chainability
	  // do plugin stuff
	});
})(jQuery, window);

First, we create a self-calling anonymous function to avoid using global variables. We pass in $, window, and undefined. The arguments to the self-calling function are jQuery and window; nothing is passed in for undefined, so if we decide to use the undefined keyword in the plugin, "undefined" will actually is undefined.

This prevents other scripts from potentially assigning malicious values ??to undefined, such as true!

$ Passed as jQuery; we do this to ensure that $ can still fully reference something else, such as a Prototype, outside of the anonymous function.

Passing variables of a globally accessible window object allows more code to be compressed through the minification process (which you should also do).

Next, we use the jQuery plug-in mode, $.fn.PluginName. This is how to register a plugin to use the $(selector).method() format. It just extends jQuery's prototype with your new methods. If you want to create a plugin that defines a function on a jQuery object, add it directly like this:

$.PluginName = function(options){
	// extend options, do plugin stuff
}

This type of plug-in cannot be linked because functions defined as properties of jQuery objects generally do not return jQuery objects. For example, consider the following code:

$.splitInHalf = function(stringToSplit){
	var length = stringToSplit.length;
	var stringArray = stringToSplit.split(stringToSplit[Math.floor(length/2)]);
	return stringArray;
}

Here, we return an array of strings. It makes sense to simply return it as an array, since that's probably what the user will want to use (and they can easily wrap it in a jQuery object if they want). Instead, consider the following contrived example:

$.getOddEls = function(jQcollection){ //
	return jQcollection.filter(function(index){
		var i = index+1;
		return (index % 2 != 0);
	});
}

In this case, the user may expect a jQuery object returned from $.getOddEls; therefore, we return the filter method, which returns the jQuery collection defined by the passed function. A good rule of thumb is to wrap returned elements in jQuery functions, especially if they can be chained; if you are returning arrays, strings, numbers, functions, or other data types, leave them open.


2 - You are not (correctly) documenting your code

Arguably the most important thing you can do when publishing code is add the necessary documentation. The gap between what you explain to developers and what the code actually does or can do is that users don't want to waste time figuring out the ins and outs of the code.

Documentation is a practice without any hard and fast rules; however, it is generally accepted that the more (well-organized) documentation you have, the better.

This process should be both an internal practice (in/scattered throughout the code) and an external practice (thorough explanation of every public method, option, and multiple use cases in a wiki or readme file).


3 - You are not providing enough flexibility or customizability

The most popular plugins provide full access to variables that the user may want to control (called "options" objects in most plugins). They may also provide many different configurations of the plugin so that it can be reused in many different contexts. For example, let's consider a simple slider plugin. Options the user may wish to control include the speed, type, and delay of the animation.

It's a good idea to also give users access to the class/ID names added to the DOM elements inserted or manipulated by the plugin. But in addition, they may want to access the callback function on every slide transition, or when the slide transitions back to the beginning (a complete "loop").

Your job is to consider all possible uses and needs for your plugin.

Let's consider another example: the plugin calling the API should provide access to the API's return object. Take the following simple plug-in concept as an example:

$.fn.getFlickr = function(opts) {
	return this.each(function(){ // jQuery chainability
		var defaults = { // setting your default options
			cb : function(data){},
			flickrUrl : // some default value for an API call
		}
	    // extend the options from defaults with user's options
	    var options = $.extend(defaults, opts || {});

	    // call the async function and then call the callback
	    // passing in the api object that was returned
	    $.ajax(flickrUrl, function(dataReturned){
			options.cb.call(this, dataReturned);
		});
	});
}

這使我們能夠做以下事情:

	$(selector).getFlickr(function(fdata){ // flickr data is in the fdata object });

宣傳這一點的另一種方式是提供“鉤子”作為選項。從 jQuery 1.7.1 及更高版本開始,我們可以在插件調(diào)用之后使用 .on(eventName, function(){}) 將行為分離到它們自己的函數(shù)中。例如,使用上面的插件,我們可以將代碼更改為如下所示:

$.fn.getFlickr = function(opts) {
	return this.each(function(i,el){
		var $this = el;
		var defaults = { // setting your default options
			flickrUrl : "http://someurl.com" // some default value for an API call
		}
	    var options = $.extend(defaults, opts || {});

	    // call the async function and then call the callback
	    // passing in the api object that was returned
	    $.ajax(flickrUrl, function(dataReturned){
	    	// do some stuff
			$this.trigger("callback", dataReturned);
		}).error(function(){
				$this.trigger("error", dataReturned);
			});
	});
}

這允許我們調(diào)用 getFlickr 插件并鏈接其他行為處理程序。

$(selector).getFlickr(opts).on("callback", function(data){ // do stuff }).on("error", function(){ // handle an error });

您可以看到提供這種靈活性絕對重要;您的插件的操作越復雜,可用的控件就越復雜。


4 - 您需要太多配置

好的,第三條建議是,您的插件的操作越復雜,可用的控制就越復雜。可用。然而,一個很大的錯誤是為插件功能提供了太多的選項。例如,基于 UI 的插件最好具有無參數(shù)默認行為。

$(selector).myPlugin();

當然,有時這是不現(xiàn)實的(例如,用戶可能正在獲取特定的提要)。在這種情況下,您應該為他們做一些繁重的工作。有多種方式將選項傳遞給插件。例如,假設我們有一個簡單的推文獲取器插件。該推文獲取器應該有一個默認行為,帶有一個必需選項(您要從中獲取的用戶名)。

$(selector).fetchTweets("jcutrell");

例如,默認情況下可能會抓取一條推文,將其包裝在段落標記中,然后使用該 html 填充選擇器元素。這是大多數(shù)開發(fā)人員所期望和欣賞的行為。細粒度選項應該就是:選項。


5 - 您正在混合外部 CSS 規(guī)則和內(nèi)聯(lián) CSS 規(guī)則

當然,根據(jù)插件的類型,如果高度基于 UI 操作,則必須包含 CSS 文件,這是不可避免的。一般來說,這是一個可以接受的問題解決方案;大多數(shù)插件都與圖像和 CSS 捆綁在一起。但不要忘記第二點 - 文檔還應包括如何使用/引用樣式表和圖像。開發(fā)人員不想浪費時間查看源代碼來弄清楚這些事情。

事情應該只是......工作。

話雖如此,使用注入樣式(可以通過插件選項高度訪問)或基于類/ID 的樣式絕對是最佳實踐。這些 ID 和類也應該可以通過前面提到的選項進行訪問。然而,內(nèi)聯(lián)樣式會覆蓋外部 CSS 規(guī)則;不鼓勵將兩者混合使用,因為開發(fā)人員可能需要很長時間才能弄清楚為什么插件創(chuàng)建的元素不遵守他們的 CSS 規(guī)則。在這些情況下請運用您的最佳判斷。

根據(jù)經(jīng)驗,內(nèi)聯(lián) CSS 很糟糕 - 除非它很小到無法保證有自己的外部樣式表。


6 - 你沒有提供示例

證據(jù)就在布丁中:如果您無法提供一個實際示例來說明您的插件如何使用隨附的代碼,人們很快就會放棄使用您的插件。就那么簡單。不要偷懶。

一個很好的示例模板:

  • “hello world”示例 - 通常是傳遞最小配置/選項的插件調(diào)用,并且附帶 html/css
  • 一些更復雜的示例 - 通常包含多個選項的完整功能的示例
  • 集成示例 - 如果有人可能將另一個插件與您的插件一起使用,您可以在此處展示如何執(zhí)行此操作。 (這也能讓你在開源開發(fā)領域獲得加分。值得贊揚。)

7 - 你的代碼與他們的 jQuery 版本不匹配

jQuery,像任何優(yōu)秀的代碼庫一樣,隨著每個版本的發(fā)布而成長。即使在棄用支持后,大多數(shù)方法仍會保留。然而,添加了新的方法;一個完美的例子是 .on() 方法,它是 jQuery 的新的事件委托一體化解決方案。如果您編寫一個使用 .on() 的插件,那么使用 jQuery 1.6 或更早版本的人將不走運?,F(xiàn)在,我并不是建議您針對最低公分母進行編碼,但是,在您的文檔中,請務必解釋您的插件支持哪個版本的 jQuery。如果您引入了支持 jQuery 1.7 的插件,那么即使 1.8 發(fā)布,您也應該強烈考慮維持對 1.7 的支持。您還應該考慮利用 jQuery 中新的/更好的/更快的功能。

鼓勵開發(fā)人員升級,但不要太頻繁地破壞您的插件!一種選擇是提供插件的“舊版”、已棄用、不受支持的版本。


8 - 變更日志在哪里?

如果您還沒有學會如何使用版本控制,那么是時候咬緊牙關(guān)了。

除了將 jQuery 版本支持/兼容性作為文檔的一部分之外,您還應該進行版本控制。版本控制(具體來說,通過 GitHub)在很大程度上是社交編碼的發(fā)源地。如果您正在開發(fā)一個 jQuery 插件并希望最終發(fā)布到官方存儲庫中,那么無論如何它都必須存儲在 GitHub 存儲庫中;如果您還沒有學會如何使用版本控制,那么是時候硬著頭皮了。版本控制有無數(shù)的好處,所有這些都超出了本文的范圍。但核心好處之一是,它允許人們查看您所做的更改、改進和兼容性修復以及您何時進行這些更改、改進和兼容性修復。這也為您編寫的插件的貢獻和定制/擴展打開了大門。

其他資源

  • Git 書
  • 使用 Git 輕松進行版本控制
  • 使用 Git、GitHub 和 SSH 的完美工作流程
  • 熟練使用 Git (19 美元)
  • GitCast

9 - 沒有人需要你的插件

世界不需要另一個滑塊插件。

好吧,我們在這里忽略它已經(jīng)足夠長的時間了:一些“插件”是無用的或太淺,不足以保證被稱為插件。世界不需要另一個滑塊插件!然而,應該指出的是,內(nèi)部團隊可能會開發(fā)自己的插件供自己使用,這是完全可以的。但是,如果您希望將您的插件推向社交編碼領域,請找到編寫更多代碼的理由。俗話說,沒有理由重新發(fā)明輪子。相反,接過別人的方向盤,建造一輛賽車。當然,有時會有新的、更好的方法來做已經(jīng)做過的同樣的事情。例如,如果您使用更快或新技術(shù),您很可能會編寫一個新的滑塊插件。


10 - 您沒有提供縮小版本

這個相當簡單:提供代碼的縮小版本。這使得它更小、更快。它還確保您的 Javascript 在編譯時不會出現(xiàn)錯誤。當您縮小代碼時,不要忘記也提供未壓縮的版本,以便您的同行可以查看底層代碼。對于各種經(jīng)驗水平的前端開發(fā)人員來說,都有免費且廉價的工具。

有關(guān)自動化解決方案,請參閱提示十三。


11 - 你的代碼太聰明了

當你編寫一個插件時,它的目的就是供其他人使用,對嗎?因此,最有效的源代碼是具有高度可讀性的。如果您正在編寫無數(shù)巧妙的單行 lambda 樣式函數(shù),或者您的變量名稱沒有語義,那么當錯誤不可避免地發(fā)生時,將很難對其進行調(diào)試。不要編寫短變量名來節(jié)省空間,而是遵循技巧九(縮小?。┲械慕ㄗh。這是優(yōu)秀文檔的另一部分;優(yōu)秀的開發(fā)人員應該能夠檢查您的代碼并了解其用途,而無需花費太多精力。

如果您發(fā)現(xiàn)自己調(diào)用變量“a”或“x”,那么您就做錯了。

此外,如果您發(fā)現(xiàn)自己查閱文檔來記住您自己的看起來奇怪的代碼正在做什么,那么您也可能需要不那么簡潔并更具解釋性。將每個函數(shù)的行數(shù)限制為盡可能少;如果它們延伸三十行或更多行,則可能會有代碼味道。


11.你不需要 jQuery

盡管我們都喜歡使用 jQuery,但重要的是要了解它是一個庫,而且成本很小。一般來說,您不需要太擔心 jQuery 選擇器性能之類的事情。不要令人討厭,你會沒事的。 jQuery 是高度優(yōu)化的。也就是說,如果您需要 jQuery(或插件)的唯一原因是在 DOM 上執(zhí)行一些查詢,您可能會考慮完全刪除抽象,而堅持使用普通 JavaScript 或 Zepto。

注意:如果您決定堅持使用普通 JavaScript,請確保您使用的是跨瀏覽器的方法。對于較新的 API,您可能需要一個小型的 polyfill。


13 - 您沒有自動化該過程

使用咕嚕聲。期間。

Grunt 是一個“用于 JavaScript 項目的基于任務的命令行構(gòu)建工具”,最近在 Nettuts+ 上對此進行了詳細介紹。它允許你做這樣的事情:

grunt init:jquery

此行(在命令行中執(zhí)行)將提示您一系列問題,例如標題、描述、版本、git 存儲庫、許可證等。這些信息有助于自動化設置文檔、許可等的過程。

Grunt 所做的不僅僅是為您制作一些定制的樣板代碼;它還提供內(nèi)置工具,例如代碼 linter JSHint,只要您安裝了 PhantomJS(由 Grunt 負責),它就可以為您自動執(zhí)行 QUnit 測試。這樣,您可以簡化工作流程,因為測試在保存時會立即在終端中運行。


14 - Вы не проверяли

А, кстати, вы проверяли свой код, верно? Если нет, то как вы гарантируете/заявляете, что ваш код работает должным образом? Ручное тестирование имеет свое место, но если вы обнаруживаете, что обновляете браузер бесчисленное количество раз в час, вы делаете это неправильно. Рассмотрите возможность использования таких инструментов, как QUnit, Jasmine или даже Mocha.

Тесты особенно полезны при объединении запросов на включение на GitHub. Вы можете потребовать, чтобы все запросы предоставляли тесты, чтобы гарантировать, что новый/измененный код не нарушит работу существующих плагинов.

Если концепция тестирования плагинов jQuery для вас нова, посмотрите нашу эксклюзивную демонстрацию Premium ?Тестирование технологии, которая управляет плагинами jQuery?. Кроме того, позднее на этой неделе мы запускаем на веб-сайте новый курс ?Тестирование JavaScript с помощью Jasmine?!


Несколько полезных ресурсов

Мы не принесем вам никакой пользы, если просто расскажем, что вы сделали не так. Вот несколько ссылок, которые вернут вас на правильный путь!

  • Изучите jQuery за 30 дней
  • Базовый шаблон плагина jQuery - Smashing Magazine
  • Использование шаблона наследования для организации больших приложений jQuery
  • Официальная документация jQuery для создания плагинов
  • Шаблон jQuery
  • ООП шаблон плагина jQuery
  • 10 советов по написанию продвинутых плагинов jQuery

Заключение

Если вы пишете плагин jQuery, крайне важно избегать ошибок, перечисленных выше. Пропустил ли я какие-либо ключевые признаки того, что плагин работает плохо?

The above is the detailed content of 14 Possible Explanations Why Your jQuery Plugin Is Not Used. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
How to diagnose high CPU usage caused by WordPress How to diagnose high CPU usage caused by WordPress Jul 06, 2025 am 12:08 AM

The main reasons why WordPress causes the surge in server CPU usage include plug-in problems, inefficient database query, poor quality of theme code, or surge in traffic. 1. First, confirm whether it is a high load caused by WordPress through top, htop or control panel tools; 2. Enter troubleshooting mode to gradually enable plug-ins to troubleshoot performance bottlenecks, use QueryMonitor to analyze the plug-in execution and delete or replace inefficient plug-ins; 3. Install cache plug-ins, clean up redundant data, analyze slow query logs to optimize the database; 4. Check whether the topic has problems such as overloading content, complex queries, or lack of caching mechanisms. It is recommended to use standard topic tests to compare and optimize the code logic. Follow the above steps to check and solve the location and solve the problem one by one.

How to minify JavaScript files in WordPress How to minify JavaScript files in WordPress Jul 07, 2025 am 01:11 AM

Miniving JavaScript files can improve WordPress website loading speed by removing blanks, comments, and useless code. 1. Use cache plug-ins that support merge compression, such as W3TotalCache, enable and select compression mode in the "Minify" option; 2. Use a dedicated compression plug-in such as FastVelocityMinify to provide more granular control; 3. Manually compress JS files and upload them through FTP, suitable for users familiar with development tools. Note that some themes or plug-in scripts may conflict with the compression function, and you need to thoroughly test the website functions after activation.

How to prevent comment spam programmatically How to prevent comment spam programmatically Jul 08, 2025 am 12:04 AM

The most effective way to prevent comment spam is to automatically identify and intercept it through programmatic means. 1. Use verification code mechanisms (such as Googler CAPTCHA or hCaptcha) to effectively distinguish between humans and robots, especially suitable for public websites; 2. Set hidden fields (Honeypot technology), and use robots to automatically fill in features to identify spam comments without affecting user experience; 3. Check the blacklist of comment content keywords, filter spam information through sensitive word matching, and pay attention to avoid misjudgment; 4. Judge the frequency and source IP of comments, limit the number of submissions per unit time and establish a blacklist; 5. Use third-party anti-spam services (such as Akismet, Cloudflare) to improve identification accuracy. Can be based on the website

How to enqueue assets for a Gutenberg block How to enqueue assets for a Gutenberg block Jul 09, 2025 am 12:14 AM

When developing Gutenberg blocks, the correct method of enqueue assets includes: 1. Use register_block_type to specify the paths of editor_script, editor_style and style; 2. Register resources through wp_register_script and wp_register_style in functions.php or plug-in, and set the correct dependencies and versions; 3. Configure the build tool to output the appropriate module format and ensure that the path is consistent; 4. Control the loading logic of the front-end style through add_theme_support or enqueue_block_assets to ensure that the loading logic of the front-end style is ensured.

How to add custom fields to users How to add custom fields to users Jul 06, 2025 am 12:18 AM

To add custom user fields, you need to select the extension method according to the platform and pay attention to data verification and permission control. Common practices include: 1. Use additional tables or key-value pairs of the database to store information; 2. Add input boxes to the front end and integrate with the back end; 3. Constrain format checks and access permissions for sensitive data; 4. Update interfaces and templates to support new field display and editing, while taking into account mobile adaptation and user experience.

How to add custom rewrite rules How to add custom rewrite rules Jul 08, 2025 am 12:11 AM

The key to adding custom rewrite rules in WordPress is to use the add_rewrite_rule function and make sure the rules take effect correctly. 1. Use add_rewrite_rule to register the rule, the format is add_rewrite_rule($regex,$redirect,$after), where $regex is a regular expression matching URL, $redirect specifies the actual query, and $after controls the rule location; 2. Custom query variables need to be added through add_filter; 3. After modification, the fixed link settings must be refreshed; 4. It is recommended to place the rule in 'top' to avoid conflicts; 5. You can use the plug-in to view the current rule for convenience

How to optimize WordPress robots txt How to optimize WordPress robots txt Jul 13, 2025 am 12:37 AM

robots.txt is crucial to the SEO of WordPress websites, and can guide search engines to crawl behavior, avoid duplicate content and improve efficiency. 1. Block system paths such as /wp-admin/ and /wp-includes/, but avoid accidentally blocking the /uploads/ directory; 2. Add Sitemap paths such as Sitemap: https://yourdomain.com/sitemap.xml to help search engines quickly discover site maps; 3. Limit /page/ and URLs with parameters to reduce crawler waste, but be careful not to block important archive pages; 4. Avoid common mistakes such as accidentally blocking the entire site, cache plug-in affecting updates, and ignoring the matching of mobile terminals and subdomains.

How to profile WordPress performance How to profile WordPress performance Jul 07, 2025 am 12:43 AM

1. Use performance analysis plug-in to quickly locate problems. For example, QueryMonitor can view the number of database queries and PHP errors, BlackboxProfiler generates function execution reports, and NewRelic provides server-level analysis; 2. Analyzing PHP execution performance requires checking time-consuming functions, debugging tools usage and memory allocation, such as Xdebug generates flame graphs to assist in optimization; 3. Monitor database query efficiency can be checked through slow query logs and index checks, QueryMonitor can list all SQL and sort by time; 4. Combining external tools such as GooglePageSpeedInsights, GTmetrix and WebPageTest to evaluate front-end plus

See all articles