国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home php教程 PHP開發(fā) jQuery plug-in encapsulation method

jQuery plug-in encapsulation method

Dec 06, 2016 pm 03:52 PM
jquery

Extending jQuery plug-ins and methods is very powerful and can save a lot of development time. This article will outline the basics, best practices, and common pitfalls of jQuery plugin development.

1. Getting started

Writing a jQuery plug-in starts by adding a new function attribute to jQuery.fn. The name of the object attribute added here is the name of your plug-in:

. The code is as follows:

jQuery.fn.myPlugin = function(){
//你自己的插件代碼
};

Where have the symbols that users loved so much gone? It still exists, but, in order to avoid conflicts with other JavaScript libraries, it is better to pass jQuery to a self-executing closed program, where jQuery is mapped as a symbol, so as to avoid the $ sign being overwritten by other libraries.

. The code is as follows:

(function ($) {
$.fn.myPlugin = function () {
//你自己的插件代碼
};
})(jQuery);

In this closed program, we can use the $ symbol without restriction to represent jQuery functions.

2. Environment

Now, we can start writing the actual plug-in code. However, before that, we must have an idea of ??the environment in which the plug-in is located. In the scope of the plug-in, the this keyword represents the jQuery object that the plug-in will execute. A common misunderstanding is easy to occur here, because in other jQuery functions that contain callbacks, the this keyword represents the native DOM element. This often causes developers to mistakenly wrap the this keyword in jQuery unnecessarily, as shown below.

. The code is as follows:

(function ($) {
$.fn.myPlugin = function () {
//此處沒有必要將this包在$號中如$(this),因為this已經(jīng)是一個jQuery對象。
//$(this)等同于 $($('#element'));
this.fadeIn('normal', function () {
//此處callback函數(shù)中this關鍵字代表一個DOM元素
});
};
})(jQuery);
$('#element').myPlugin();

3. Basic knowledge

Now that we understand the basics of jQuery plug-ins, let’s write a plug-in to do something.

. The code is as follows:

(function ($) {
$.fn.maxHeight = function () {
var max = 0;
this.each(function () {
max = Math.max(max, $(this).height());
});
return max;
};
})(jQuery);
var tallest = $('div').maxHeight(); //返回高度最大的div元素的高度
   
這是一個簡單的插件,利用.height()返回頁面中高度最大的div元素的高度。

4. Maintain Chainability

Many times, the intention of a plug-in is simply to modify the collected elements in some way and pass them to the next method in the chain. This is the beauty of jQuery's design and one of the reasons jQuery is so popular. Therefore, to maintain a plugin's chainability, you must ensure that your plugin returns the this keyword.

. The code is as follows:

(function ($) {
$.fn.lockDimensions = function (type) {
return this.each(function () {
var $this = $(this);
if (!type || type == 'width') {
$this.width($this.width());
}
if (!type || type == 'height') {
$this.height($this.height());
}
});
};
})(jQuery);
$('div').lockDimensions('width').CSS('color', 'red');

Since the plugin returns this keyword, it maintains chainability, so that elements collected by jQuery can continue to be controlled by jQuery methods such as .css. Therefore, if your plugin does not return an intrinsic value, you should always return the this keyword within its scope. Additionally, you might deduce that parameters passed to a plugin will be passed within the plugin's scope. Therefore, in the previous example, the string 'width' becomes a type parameter of the plugin.

5. Default values ??and options

For plugins that are more complex and provide many customizable options, it is best to have a default setting that can be extended when the plugin is called (by using $.extend). So instead of calling a plugin with a bunch of parameters, you can call it with an object parameter containing the settings you want to override.

. The code is as follows:

(function ($) {
$.fn.tooltip = function (options) {
//創(chuàng)建一些默認值,拓展任何被提供的選項
var settings = $.extend({
'location': 'top',
'background-color': 'blue'
}, options);
return this.each(function () {
// Tooltip插件代碼
});
};
})(jQuery);
$('div').tooltip({
'location': 'left'
});

In this example, when calling the tooltip plug-in, the location option in the default settings is overwritten, and the background-color option remains at its default value, so the final called setting value is:

. The code is as follows:

{
'location': 'left',
'background-color': 'blue'
}

This is a very flexible way to provide a highly configurable plugin without the developer having to define all the available options.

6. Namespace

Correctly naming your plug-in is a very important part of plug-in development. With the right namespace, you can guarantee that your plugin will have a very low chance of being overwritten by other plugins or other code on the same page. Namespaces also make your life as a plugin developer easier because it helps you better keep track of your methods, events, and data.

7. Plug-in methods

In any case, a single plug-in should not have multiple namespaces in the jQuery.fnjQuery.fn object.

. The code is as follows:

(function ($) {
$.fn.tooltip = function (options) {
// this
};
$.fn.tooltipShow = function () {
// is
};
$.fn.tooltipHide = function () {
// bad
};
$.fn.tooltipUpdate = function (content) {
// !!!
};
})(jQuery);

This is discouraged because .fn clutters the .fn namespace. To solve this problem, you should collect all the plugin's methods in the object text and call them by passing the string name of the method to the plugin.

. The code is as follows:

(function ($) {
var methods = {
init: function (options) {
// this
},
show: function () {
// is
},
hide: function () {
// good
},
update: function (content) {
// !!!
}
};
$.fn.tooltip = function (method) {
// 方法調(diào)用
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.tooltip');
}
};
})(jQuery);
//調(diào)用init方法
$('div').tooltip();
//調(diào)用init方法
$('div').tooltip({
foo: 'bar'
});
// 調(diào)用hide方法
$(‘div').tooltip(‘hide');
//調(diào)用Update方法
$(‘div').tooltip(‘update', ‘This is the new tooltip content!');

This type of plugin architecture allows you to encapsulate all methods in a parent package and call them by passing the string name of the method and the additional parameters required by this method. This type of encapsulation and architecture is standard in the jQuery plug-in community, and it is used by countless plug-ins, including plug-ins and widgets in jQuery UI.

8. Events

A little-known function of the bind method allows binding event namespaces. If your plugin binds an event, a good practice is to namespace this event. This way, when you unbind, you won't interfere with other events of the same type that may already be bound. You can do this by appending the namespace to the event you need to bind via '.'.

. The code is as follows:

(function ($) {
var methods = {
init: function (options) {
return this.each(function () {
$(window).bind('resize.tooltip', methods.reposition);
});
},
destroy: function () {
return this.each(function () {
$(window).unbind('.tooltip');
})
},
reposition: function () {
//...
},
show: function () {
//...
},
hide: function () {
//...
},
update: function (content) {
//...
}
};
$.fn.tooltip = 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.tooltip');
}
};
})(jQuery);
$('#fun').tooltip();
//一段時間之后… …
$(‘#fun').tooltip(‘destroy');

在這個例子中,當tooltip通過init方法初始化時,它將reposition方法綁定到resize事件并給reposition非那方法賦予命名空間通過追加.tooltip。 稍后, 當開發(fā)人員需要銷毀tooltip的時候,我們可以同時解除其中reposition方法和resize事件的綁定,通過傳遞reposition的命名空間給插件。 這使我們能夠安全地解除事件的綁定并不會影響到此插件之外的綁定。

九、數(shù)據(jù)

通常在插件開發(fā)的時候,你可能需要記錄或者檢查你的插件是否已經(jīng)被初始化給了一個元素。 使用jQuery的data方法是一個很好的基于元素的記錄變量的途徑。盡管如此,相對于記錄大量的不同名字的分離的data, 使用一個單獨的對象保存所有變量,并通過一個單獨的命名空間讀取這個對象不失為一個更好的方法。

. 代碼如下:

(function ($) {
var methods = {
init: function (options) {
return this.each(function () {
var $this = $(this),
data = $this.data('tooltip'),
tooltip = $(&#39;<div />&#39;, {
text: $this.attr(&#39;title&#39;)
});
// If the plugin hasn&#39;t been initialized yet
if (!data) {
/*
Do more setup stuff here
*/
$(this).data(&#39;tooltip&#39;, {
target: $this,
tooltip: tooltip
});
}
});
},
destroy: function () {
return this.each(function () {
var $this = $(this),
data = $this.data(&#39;tooltip&#39;);
// Namespacing FTW
$(window).unbind(&#39;.tooltip&#39;);
data.tooltip.remove();
$this.removeData(&#39;tooltip&#39;);
})
},
reposition: function () {
// ...
},
show: function () {
// ...
},
hide: function () {
// ...
},
update: function (content) {
// ...
}
};
$.fn.tooltip = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === &#39;object&#39; || !method) {
return methods.init.apply(this, arguments);
} else {
$.error(&#39;Method &#39; + method + &#39; does not exist on jQuery.tooltip&#39;);
}
};
})(jQuery);

將數(shù)據(jù)通過命名空間封裝在一個對象中,可以更容易的從一個集中的位置讀取所有插件的屬性。

十、總結(jié)和最佳做法

編寫jQuery插件允許你做出庫,將最有用的功能集成到可重用的代碼,可以節(jié)省開發(fā)者的時間,使開發(fā)更高效。 開發(fā)jQuery插件時,要牢記:

1.始終包裹在一個封閉的插件:

. 代碼如下:

(function($) {
/* plugin goes here */
})(jQuery);

2.不要冗余包裹this關鍵字在插件的功能范圍內(nèi)

3.除非插件返回特定值,否則總是返回this關鍵字來維持chainability 。

4.傳遞一個可拓展的默認對象參數(shù)而不是大量的參數(shù)給插件。

5.不要在一個插件中多次命名不同方法。

3.始終命名空間的方法,事件和數(shù)據(jù)。

最后加一個自己寫的放大鏡的插件`

(function($){$.fn.Fdj=function(){
$(&#39;#smallImg&#39;).on(&#39;mouseover&#39;, function() {
$(&#39;#slider&#39;).show();
})
$(&#39;#smallImg&#39;).on(&#39;mouseout&#39;, function() {
$(&#39;#slider&#39;).hide();
})
$(&#39;#smallImg&#39;).on(&#39;mousemove&#39;, function(e) {
var x = e.clientX - $(&#39;#slider&#39;).width() / 2;
var y = e.clientY - $(&#39;#slider&#39;).height() / 2;
if(x <= 0) {
x = 0
}
if(x > $(&#39;#smallImg&#39;).width() - $(&#39;#slider&#39;).width()) {
x = $(&#39;#smallImg&#39;).width() - $(&#39;#slider&#39;).width();
}
if(y <= 0) {
y = 0
}
if(y > $(&#39;#smallImg&#39;).height() - $(&#39;#slider&#39;).height()) {
y = $(&#39;#smallImg&#39;).height() - $(&#39;#slider&#39;).height();
}
$(&#39;#slider&#39;).css({
&#39;left&#39;: x,
&#39;top&#39;: y
})
var X=x/$(&#39;#smallImg&#39;).width()*800
var Y=y/$(&#39;#smallImg&#39;).height()*800
$(&#39;#img&#39;).css({
left:-X,
top:-Y
})
})
}
})(jQuery)

? ?


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)

Detailed explanation of jQuery reference methods: Quick start guide Detailed explanation of jQuery reference methods: Quick start guide Feb 27, 2024 pm 06:45 PM

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

In-depth analysis: jQuery's advantages and disadvantages In-depth analysis: jQuery's advantages and disadvantages Feb 27, 2024 pm 05:18 PM

jQuery is a fast, small, feature-rich JavaScript library widely used in front-end development. Since its release in 2006, jQuery has become one of the tools of choice for many developers, but in practical applications, it also has some advantages and disadvantages. This article will deeply analyze the advantages and disadvantages of jQuery and illustrate it with specific code examples. Advantages: 1. Concise syntax jQuery's syntax design is concise and clear, which can greatly improve the readability and writing efficiency of the code. for example,

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ??the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

How to remove the height attribute of an element with jQuery? How to remove the height attribute of an element with jQuery? Feb 28, 2024 am 08:39 AM

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

Introduction to how to add new rows to a table using jQuery Introduction to how to add new rows to a table using jQuery Feb 29, 2024 am 08:12 AM

jQuery is a popular JavaScript library widely used in web development. During web development, it is often necessary to dynamically add new rows to tables through JavaScript. This article will introduce how to use jQuery to add new rows to a table, and provide specific code examples. First, we need to introduce the jQuery library into the HTML page. The jQuery library can be introduced in the tag through the following code:

See all articles