How to write a Plugin plugin for Jquery
Blog Categories:JQuery Plugin plug-ins, if you don't know what a JQuery plug-in is or how to write a website where you can view it officially: jQuery Authoring Guidelines
Okay, here are some requirements that I feel I must have in order to be a good plugin:
1. Declare only a single name in the JQuery namespace
2. Accept options parameters to control plug-in behavior
3. Expose the default settings of the plug-in so that it can be accessed outside
4. Provide subfunctions appropriately to external access calls
5. Keep Private Functions
6. Support metadata plug-in
The following will be done one by one:
Declare only a single name
This indicates a separate plug-in script.If your script contains multiple or complementary plug-ins (such as $.fn.doSomething() and $.undoSomething()), you can declare multiple names as required.Typically, however, a single name is strived to maintain all the details of the plug-in's reality.
In this case, we'll declare a name called "hilight"
- //Definition of plug-ins
- $.fn.hilight = function( options ){
- //Here's the implementation code for the plug-in...
- };
Then we can call it like this:
- $("divTest").hilight();
Accept an option parameter to control the behavior of the plug-in
- $.fn.hilight = function(options){
- var defaults = {
- foreground : 'red',
- background : 'yellow'
- };
- //Extends out defaults options with those privided Extend our default settings
- $.extend(defaults,options);
- };
And we can use it like this:
- $('#myDiv').hilight({
- foreground: 'blue'
- });
Expose the plug-in's default settings so they are accessible outside
As a promotion and optimization of plug-ins, we should expose the code above as the default settings for plug-ins.
This is important so that users of the plug-in can easily rewrite or customize it with minimal code.However, we can take advantage of the JavaScript function object:
- $.fn.hilight = function(options){
- //Extend our default options with those provided
- //Note that the first arg to extend is an empty object
- //this is to keep from overriding our "defaults" object
- var opts = $.extend({},$.fn.hilight.defaults,options);
- }
- $.fn.hilight.defaults = {
- foreground : 'red',
- background : 'yellow'
- };
It is worth noting here that the first parameter of $.extend() is an empty object, which allows us to override the plug-in's default settings
Users can use plug-ins like this:
- // override plugin default foreground color
- $.fn.hilight.defaults.foreground = 'blue';
- // ...
- // invoke plugin using new defaults
- $('.hilightDiv').hilight();
- // ...
- // override default by passing options to plugin method
- $('#green').hilight({
- foreground: 'green'
- });
Provide subfunctions appropriately to external access calls
Continuing with the previous example, you will find an interesting way to extend your plug-in (and then let others extend your plug-in:).For example, we have declared a function called "format" in our plug-in to highlight this display text. Our plug-in implementation code might look like this:
- $.fn.hight = function(options){
- //iterate and reformat each mached element
- return this.each(function(){
- var $this = $(this);
- //...
- var markup = $this.html();
- //call our format function
- markup = $.fn.hilight.format(markup);
- $this.html(markup);
- });
- };
- //define our format function
- $.fn.hilight.format = function(txt){
- return '<strong>' + txt + '</strong>';
- };
Keep Private Functions
Exposing parts of your plug-in to provide overrides may seem very powerful, but you must carefully consider which parts of your plug-in need to be exposed.Once exposed, you need to consider these points of change, and in general, if you're not sure which parts need to be exposed, you can avoid doing so.
So how can you define more functions without exposing them?Leave the task to the closure.To verify, we add a function called "debug" to the plug-in that will record the number of elements selected to the FireBug console.To create a closure, we wrap the entire definition of the plug-in:
- //create closure
- (function($){
- //plugin definition
- $.fn.hilight = function(options){
- debug(this);
- //...
- };
- //private function for debuggin
- function debug($obj){
- if(window.console && window.console.log){
- window.console.log('hilight selection count :' + $obj.size());
- }
- }
- //...
- //end of closure
- })(jQuery);
This way the "debug" method cannot be called outside of the closure
Supports metadata plug-ins
Depending on the type of plug-in you write, and supporting metadata plug-ins makes them more powerful.Personally, I like element data plugins because they allow you to separate tags and override their configuration (which is especially useful when writing demo s and examples).Most importantly, it's especially easy to think about it!
- $.fn.hilight = function(options){
- //build main options before element interation
- var opts = $.extend({},$.fn.hilight.defaults,options);
- return this.each(function(){
- var $this = $(this);
- //build element specific options
- var o = $.meta ? $.extend({},opts,$this.data()) : opts;
- //In general, develop metadata support capabilities.
- });
- }
A few line changes accomplish the following things:
1. Detect if metadata is configured
2. Extend configuration properties with additional metadata if configured
- <!-- markup -->
- <div class="hilight { background: 'red', foreground: 'white' }">
- Have a nice day!This is metadata
- </div>
- <div class="hilight { foreground: 'orange' }">
- Have a nice day!Configure in Tags
- </div>
- <div class="hilight { background: 'green' }">
- Have a nice day!
- </div>
Then we can highlight these div tags separately according to the metadata configuration with a script:
- $('.hilight').hilight();
Finally, put all the code together:
- //
- //create closure
- //
- (function($){
- //
- // plugin definition
- //
- $.fn.hilight = function(options){
- debug(this);
- //build main options before element iteration
- var opts = $.extend({}, $.fn.hilight.defaults, options);
- //iterate and reformat each matched element
- return this.each(function(){
- $this = $(this);
- //build element specific options
- var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
- //update element styles
- $this.css({
- backgroundColor: o.background,
- color: o.foreground
- });
- var markup = $this.html();
- //call our format function
- });
- }
- //
- // private function for debugging
- //
- function debug($obj){
- if(window.console && window.console.log){
- window.console.log('hilight selection count: ' + $obj.size());
- }
- };
- //
- // define and expose our format function
- //
- $.fn.hilight.format = function(txt){
- return '<strong>' + txt + '</strong>';
- };
- //
- // plugin defaults
- //
- $.fn.hilight.defaults = {
- foreground : 'red',
- background : 'yellow'
- };
- //
- // end of clousure
- //
- })(jQuery);
2.
How to write a Plugin plugin for Jquery
Recent projects want a jquery plug-in to control accounting number input, found for a long time can not find, no way to do it, only their own knife in battle, in fact, the requirements are not high, that is:
1. Default: 0.00
2. Only numbers and decimal points can be entered, other inputs will be ignored.
3. Keep two decimal places automatically after entering an integer
4. You can define how many decimal places you want to keep
OK, get started:
First, by encapsulating a function as a jquery plugin package, you can easily use this package in a variety of projects and pages, and code management is easy to maintain. Also, jquery's plugin implementation is very simple, so why not? If you're new to development, read this article first: How jQuery Works
1. Basic framework of Jquery Plugin
- (function($) {
- $.fn.extend({
- MyPlugin: function(options) {
- var defaults = {
- decimal_length: 2,
- };
- var options = $.extend(defaults, options);
- var len = parseInt(options['decimal_length']);
- return this.each(function() {
- alert('edison');
- });
- }
- });
- })(jQuery);
Where options is the parameter and is called by:
- $('#ddd').MyPlugin({decimal_length:2});
Okay, let's go ahead and do what we need: the file name is money.js
- (function($) {
- var pasteEventName = ($.browser.msie ? 'paste' : 'input') + ".mask";
- $.fn.extend({
- money_type: function(options) {
- var defaults = {
- decimal_length: 2,
- };
- var options = $.extend(defaults, options);
- var len = parseInt(options['decimal_length']);
- return this.each(function() {
- var input = $(this);
- function caret() {
- var input_value = input.val();
- var reCat = /\d+\.?\d{0,2}/i;
- var_new_value = reCat.exec(input_value);
- input.val(var_new_value);
- }
- input.bind("click", function(e) {
- if (input.val() == '0.00') {
- input.select();
- }
- })
- .bind(pasteEventName, function() {
- setTimeout(caret, 0);
- });
- });
- }
- });
- })(jQuery);
OK, plug-in complete, include this file and jquery file when using it, then call it with the following code
- $('#ddd').money_type();//Keep two decimal places by default
Reprinted at: https://www.cnblogs.com/leekenky/p/4088843.html