Home > Web Front-end > JS Tutorial > Some thoughts and experiences on javascript plug-in development_javascript skills

Some thoughts and experiences on javascript plug-in development_javascript skills

WBOY
Release: 2016-05-16 15:13:08
Original
1384 people have browsed it

Cause

If you have done some front-end development work, you will definitely have this experience: when a page needs a certain effect or plug-in, we usually have two choices:
1. Search the Internet for relevant JS plug-ins and learn their usage
2. Invent your own wheels and develop plug-ins.

Look for existing plugins

The first way is to search for JS plug-ins online
In this way, you would be very lucky if there is a plug-in that just meets the needs of the project. But I believe that in most cases, the plug-ins we find will have the following problems:
(1) UI customization: The UI provided by many plug-ins does not match our project design style at all. The written html and css may not conform to the way the plug-in is used. As a result, we have to modify the html and css to adapt to the usage of the plug-in.
(2) Learning cost: If it is a more complex plug-in, there is a learning cost problem. You have to learn how to use the plug-in.
(3) The plug-in does not meet the requirements: The plug-in we found is not completely guaranteed to meet the needs of our project. At this time, you may have to modify its code to support the project requirements. This is also a possible problem
(4) The plug-in function is too large and comprehensive: Suppose your project needs a simple carousel plug-in, and you find a very awesome carousel plug-in with various cool effects, and it happens to be usable, but this plug-in has The size is about the same as that of a js library, and if you write the effects yourself, you can actually do it with just a few dozen lines of code. Is it too redundant to introduce this plug-in at this time?
These are some possible problems with using js plug-ins. Of course, the specific situation will be analyzed in detail. I am not not using already written js plug-ins. After all, some plug-ins have passed the test of time and are more beneficial to the progress of the project. If it is the following situation, I will consider using the existing js plug-in:
(1) Complex functions: such as file upload, batch upload, progress display, etc., such as HTML editor
(2) Scenarios with urgent project deadlines and low performance requirements
(3) The js plug-in just meets the needs of the project

Build your own wheel

The second approach is to create your own wheel and develop plug-ins
The main problems with writing plug-ins yourself are as follows:
(1) Developing plug-ins takes time and may delay the project schedule. This method is not recommended if the schedule is urgent
(2) Wheels made by yourself may not be as useful as existing wheels. You must consider whether your teammates are suitable
(3) A relatively high level of development is required
If the project is not urgent, I would consider building my own wheel. There are several main advantages:
(1) It fully meets the project requirements. This is obvious because the plug-in is developed completely for the project
(2) Know the basics, easy to modify, the plug-in is completely developed by yourself, and you can respond flexibly to any changes in project requirements
(3) Lightweight, because we don’t have to deal with as many needs as other open source plug-ins, so our own wheels only need to fit our own cars and do not require many changes. Relatively speaking, there are fewer changes and fewer functions, and the code is also small. There will be less.
(4) It is a great exercise for personal abilities. Don’t reinvent the wheel. This is a widely circulated saying among programmers. This has also become an excuse for many people to be lazy, but we should not use this as an excuse to hinder own steps forward. Students who have built a wheel should have a deep understanding. If you build a wheel, you will gain far more than using 100 plug-ins written by others. Our wheels may not be used in projects, but this is a very efficient learning. way, highly recommended.

How to develop a lightweight and adaptable plug-in

How to develop an adaptable and lightweight plug-in? The so-called strong applicability simply means a few points:
1. The fewer restrictions on UI, the better, preferably none
2. Does not provide too many functions, only provides simple API, allowing users to easily expand

Let’s take an example, assuming we want to develop a jQuery paging plug-in. For jQuery plug-in development tutorials, please refer to jQuery plug-in development.

Determine needs

Determining requirements is the first step in developing a plug-in. To develop a lightweight paging plug-in, we still start with the most basic needs of the plug-in. What are the most basic needs of the paging plug-in? It is nothing more than page number display and switching between page numbers. Therefore, our plug-in must Start around this basic need and forget about other needs that may exist.

Determine the plugin html and css

After determining the needs of the plug-in, the second step is the UI of the plug-in, which is html and css.
Assume the basic UI is as follows:

Seeing the basic UI above, I don’t know what kind of html structure you will think of. For us developers, html and css should be as simple as possible, so the most basic html structure is nothing more than a mixture of a tag and span tag. Some students may think of using ul and li tags, but this actually increases the complexity. Degree, the gain outweighs the loss. We write the html code as follows:

<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>
Copy after login

This is the most basic html code structure, including the container div.pager of the paging plug-in, the current page span.curPage, other page number a tags, previous page, next page and other buttons.
Next is the css code, mainly the current page tag, other page tags, previous page next page, mouse hovering on the button, etc. Several styles are written as follows:

.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; }
Copy after login

Write js code

After writing the basic html and css, the next most critical thing is the js code. First, we set up the basic form of jQuery plug-in development:

; (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);
Copy after login

Here mainly provides the default values ​​of some optional parameters, such as the default page number is 0, the number of items per page is 6, etc.
Next, let’s consider the idea of ​​paging plug-in:
1. Set the current page number to 0, which means the first page
2. Generate the html code of the paging plug-in
3. Modify the page number and generate html code
Based on this idea, we write the code as follows:

; (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);
Copy after login

There are two key points to remember in this code:
(1) Generation of html code. Since there may be too many page numbers, some page numbers need to be hidden, so we need to generate an ellipsis to represent the hidden page number, and use maxButtonCount to represent the most page number buttons
(2) Event binding, html will be regenerated every time the page number changes. We use event proxy to improve performance and eliminate the need to repeatedly bind events
Such a basic paging plug-in is enough.

But is this enough?
Suppose we need to support the function of jumping directly by entering a page number. What should we do? Do we need to modify the original HTML structure and CSS? We mentioned earlier that developing a plug-in should start with the most basic requirements, so how to deal with these potential requirements.
My solution is this, providing a simple API, no UI, and completely customized by the user.
We add three APIs to the above code: getPageIndex, setPageIndex and setItemCount, which respectively represent getting the current index, setting the current index, and setting the total number of items. The code is as follows:

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();
}
Copy after login

For the full version of the code, please view jquery.page.js
These three APIs are provided. If the user needs the function of jumping to the page number, he can directly use the setPageIndex method to jump. The UI is completely customized by the user. The plug-in itself only focuses on basic functions and does not interfere with others.
You can view DEMO

The entire plug-in code has been placed on my github. Interested students can click to view github

Summary

Finally, I will sort out my ideas for developing some js plug-ins:
1. Focus on the most basic needs themselves and ignore possible potential needs for the time being
2. Try to provide no or less UI to reduce restrictions on users
3. Consider possible potential needs and provide APIs. Potential needs are completely customized by users

These are some of my thoughts on how to be lightweight and highly applicable when writing js plug-ins. Welcome everyone to share!

This article’s address: http://luopq.com/2016/02/04/think-js-plugin/, please indicate

when reprinting
Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template