Share my thoughts and experiences on JS plugin development

Source: Internet
Author: User

This article reads the catalogue:

• Causes
• How to develop a lightweight, adaptable plug-in
• Summary

Cause

If you have done some front-end development work, there will be some experience: the page needs some kind of effect or plug-in, we generally have two options:

1, the Internet to find the relevant JS plugin, learn its usage
2, build their own wheels, the development of plug-ins.

Find plugins that exist

The first way, the Internet to find JS plugin

This is a very lucky thing if there is a plug-in that exactly matches the needs of the project. But I believe that in most cases, the plugins we find will have the following problems:

(1) UI customization: Many plugins provide UI and our project design style completely does not match, may write good HTML and CSS does not conform to the way the plug-in uses, results we also have to modify the HTML and CSS to adapt to the use of plug-ins.
(2) Learning cost: If it is a more complex plug-in, there is a learning cost problem, to learn how to use the plugin.
(3) plugin does not meet the requirements: we find the plug-in is not fully guaranteed to meet the needs of our project, this time you may have to modify its code to support the project requirements, which is also possible problems
(4) Plug-in function is too chatty: Suppose your project needs a simple carousel plug-in, the results found a very good carousel plug-in, a variety of cool effects, and just can use, but the size of the plug-in and a JS library volume is similar, and if you write the effect, in fact, as long as dozens of lines of code can be , the introduction of this plugin is too superfluous.
This is the use of JS plug-in May exist some problems, of course, specific analysis, I do not use the JS plugin has been written, after all, some plug-ins have been the test of time, the use of more conducive to the implementation of the project. If this is the case, I will consider using the existing JS plugin:

(1) Complex functions: such as file upload, batch upload, progress display, etc., such as HTML editor
(2) The project duration is urgent, the performance is not high requirements of the scene
(3) JS plugin just fits the project requirement

Build your own wheels.

The second way, build your own wheels. Develop plugins
Write your own plugin mainly has the following questions:

(1) The development of plug-ins takes time, may delay the project duration, if the duration of the emergency does not recommend the use of this method
(2) Self-made wheels may not have the use of existing wheels, to take into account the suitability of teammates
(3) need to be relatively high level of development

If the project is not urgent, I will consider making wheels, there are several main benefits:

(1) Full compliance with project requirements, this one is obvious, because the plug-in developed entirely for the project
(2) Know everything, easy to modify, plug-in is completely self-developed, the project has what needs change can be flexible to deal with
(3) Lightweight, because we do not like other open source plug-ins to deal with so many needs, so our own wheels also need to meet their own car, do not need a lot of changes, relatively speaking, change less function, less code.
(4) for personal ability is a great exercise, do not repeat the wheel that is widely circulated in the programmer's sentence, which has become a lot of people lazy excuse, but we should not use this as an excuse to hinder their progress in the footsteps. The students who made the wheel should have a deep experience, build a wheel, far more than you use other people write 100 plug-ins, our wheels can not be used in the project, but this is an extremely efficient way of learning, highly recommended.

How to develop a lightweight, adaptable plug-in

How to develop an adaptable and lightweight plug-in? The so-called applicability is strong, simply say that there are several:

1, the less the UI limit, the better, it is best not
2, does not provide too many functions, only provides the simple API, lets the user to be easy to expand

For example, let's say we want to develop a jquery page plug-in, for the jquery plugin development tutorial, refer to jquery plugin development.

Identify requirements

Identifying requirements is the first step in developing a plug-in. To develop a lightweight page plug-in, we still use the most basic requirements from the plug-in, the most basic requirements of the paging plug-in is what, nothing more than the page number display, the switch between the page number, so, our plug-in should be around the basic needs to start, and temporarily do not consider other possible needs.

Determine plugin HTML and CSS

After determining the needs of the plug-in, the second step is the UI of the plugin, HTML and CSS.

Suppose the basic UI is as follows:

Basic Page-Paging UI

See the basic UI above, do not know what kind of HTML structure you will think of. For our developers, HTML and CSS are as simple as possible, so the most basic HTML structure is nothing more than a-label and span tag mix, some students may think of using ul,li tags, but this actually increases the complexity, not worth the candle. We write the following HTML code:

?
12345678910 <div class="pager"><span class="flip noPage">上一页</span><span class="curPage">1</span><a page="1" href="javascript:;">2</a><a page="2" href="javascript:;">3</a><a page="3" href="javascript:;">4</a><span>...</span> <a href="javascript:;" page="8">9</a> <a page="1" href="javascript:;" class="flip">下一页</a></div>

This is the most basic HTML code structure, contains the page plug-in container div.pager, the current page span.curpage, other page a label, previous page, next page and other buttons.

Next is the CSS code, the main current page label, the other page label, previous page next page, hover over the button in several styles, write as follows:

?
1234567 .pager { display: inline-block; font: 12 px/21px "宋体"; margin-top: 20px; }.pager a, .pager .flip, .pager .curPage { border: 1px solid #e3e3e3; display: inline-block; height: 22px; line-height: 22px; text-align: center; }.pager a { background: none repeat scroll 0 0 #fff; color: #010101; text-decoration: none; width: 26px; }.pager a:hover { background: none repeat scroll 0 0 #f1f1f1; }.pager .noPage { color: #a4a4a4; }.pager .curPage { background: none repeat scroll 0 0 #49abde; color: #ffffff; width: 26px; }.pager .flip { width: 56px; }

Writing JS Code

Write the basic HTML and CSS, the next key is the JS code. First we build the basic form of jquery plugin development:

?
12345678910111213141516 ; (function ($, window, document, undefined) {"use strict";var defaults = {pageIndex: 0,pageSize: 6,itemCount: 50,maxButtonCount: 7,prevText: "上一页",nextText: "下一页",buildPageUrl: null,onPageChanged: null}; $.fn.pager = function (options) {options = $.extend(defaults, options || {});}})(jQuery, window, document);

Here are some of the default values for optional parameters, such as page numbers default to 0, number of 6 per page, and so on.

Then let's consider the idea of a paging plugin:

1. Set the current page number to 0, which means the first page
2. The HTML code of the raw ingredient page plugin
3, modify the page number, and then generate HTML code

Based on this idea, we write the following code:

?
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 6667686970717273747576777879808182838485 ; (function ($, window, document, undefined) {"use strict";var defaults = {pageIndex: 0,pageSize: 6,itemCount: 50,maxButtonCount: 7,prevText: "上一页",nextText: "下一页",buildPageUrl: null,onPageChanged: null};function Pager($ele, options) {this.$ele = $ele;this.options = options = $.extend(defaults, options || {});this.init();}Pager.prototype = {constructor: Pager,init: function () {this.renderHtml();this.bindEvent();},renderHtml: function () {var options = this.options;options.pageCount = Math.ceil(options.itemCount / options.pageSize);var html = [];//生成上一页的按钮if (options.pageIndex > 0) {html.push(‘<a page="‘ + (options.pageIndex - 1) + ‘" href="‘ + this.buildPageUrl(options.pageIndex + 1) + ‘" class="flip">‘ + options.prevText + ‘</a>‘);} else {html.push(‘<span class="flip noPage">‘ + options.prevText + ‘</span>‘);}//这里是关键//临时的起始页码中间页码,当页码数量大于显示的最大按钮数时使用var tempStartIndex = options.pageIndex - Math.floor(options.maxButtonCount / 2) + 1;//计算终止页码,通过max计算一排按钮中的第一个按钮的页码,然后计算出页数量var endIndex = Math.min(options.pageCount, Math.max(0, tempStartIndex) + options.maxButtonCount) - 1;var startIndex = Math.max(0, endIndex - options.maxButtonCount + 1);// 第一页if (startIndex > 0) {html.push("<a href=‘" + this.buildPageUrl(0) + "‘ page=‘" + 0 + "‘>1</a> ");html.push("<span>...</span>");}//生成页码按钮for (var i = startIndex; i <= endIndex; i++) {if (options.pageIndex == i) {html.push(‘<span class="curPage">‘ + (i + 1) + ‘</span>‘);} else {html.push(‘<a page="‘ + i + ‘" href="‘ + this.buildPageUrl(options.pageIndex + 1) + ‘">‘ + (i + 1) + ‘</a>‘);}}// 最后一页if (endIndex < options.pageCount - 1) {html.push("<span>...</span> ");html.push("<a href=‘" + this.buildPageUrl(options.pageCount - 1) + "‘ page=‘" + (options.pageCount - 1) + "‘>" + options.pageCount + "</a> ");}//生成下一页的按钮if (options.pageIndex < options.pageCount - 1) {html.push(‘<a page="‘ + (options.pageIndex + 1) + ‘" href="‘ + this.buildPageUrl(options.pageIndex + 1) + ‘" class="flip">‘ + options.nextText + ‘</a>‘);} else {html.push(‘<span class="flip noPage">‘ + options.nextText + ‘</span>‘);}this.$ele.html(html.join(""));},bindEvent: function () {var that = this;that.$ele.on("click", "a", function () {that.options.pageIndex = parseInt($(this).attr("page"), 10);that.renderHtml();that.options.onPageChanged && that.options.onPageChange(that.options.pageIndex);})},buildPageUrl: function () {if ($.isFunction(this.options.buildPageUrl)) {return this.options.buildPageUrl(pageIndex);}return "javascript:;";} };$.fn.pager = function (options) {options = $.extend(defaults, options || {});return new Pager($(this), options);}})(jQuery, window, document);

There are two key points to remember in this code:

(1) HTML code generation, because the page number may be too many, need to hide part of the page number, so we want to generate an ellipsis to indicate the page number is hidden, by Maxbuttoncount to represent the most page number button

(2) Event binding, the HTML will be regenerated each time the page number changes, we adopt the event proxy way, improve the performance, do not have to repeat the binding event
Such a basic paging plugin is already available.

But is that enough for you?

Suppose we need to support the function of inputting the page number directly, what if we need to modify the original HTML structure and CSS? As we said earlier, developing a plug-in should begin with the most basic requirements, and how to deal with these potential needs.

My solution is this, providing a simple API that does not provide UI and is completely customizable by the user.

We add three Api:getpageindex,setpageindex and Setitemcount to the code above, respectively, to get the current index, set the current index, and set the total number of items. The code is as follows:

?
123456789101112 getPageIndex: function () {return this.options.pageIndex;},setPageIndex: function (pageIndex) {this.options.pageIndex = pageIndex;this.renderHtml();},setItemCount: function (itemCount) {this.options.pageIndex = 0;this.options.itemCount = itemCount;this.renderHtml();}

Provides these three APIs, assumes the user needs to jump the page number the function, may use the Setpageindex method to jump directly, the UI is completely user-defined, the plug-in itself only focuses on the basic function, does not interfere the other.

You can view the demo

The entire plugin code has been placed on my GitHub and interested students can click to view GitHub

Summarize

Finally, I tidy up my idea of developing some JS plugins:

1, focus on the most basic needs themselves, for the time being without considering potential needs
2, try not to provide or provide less UI, reduce the restrictions on users
3. Consider potential requirements, provide APIs, and potential requirements are entirely user-defined

Share my thoughts and experiences on JS plugin development

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.