Home Web Front-end JS Tutorial JavaScript plug-in development tutorial (4)_javascript skills

JavaScript plug-in development tutorial (4)_javascript skills

May 16, 2016 pm 04:17 PM
javascript develop

1, opening analysis

Hi, do you remember the last article? It mainly talks about how a "Tab" plug-in organizes code and implements it", and the way of combining procedural design and object-oriented design

How to design a plug-in, both methods have their own advantages and disadvantages. This series of articles is learning-oriented. You can decide how to use it in specific scenarios. In this article, we still focus on the "Tab" instance,

Continue to expand related functions. Hey hey hey, stop talking nonsense and get to the point. Directly upload the actual renderings:

As you can see, a new function has been added. If during initialization, the number of entries in our module configuration information items is greater than what we specified, it will be displayed in "More Modules"

In the hidden list of operation items, our initialization parameter configuration has also been adjusted. For example, there is an additional "displayMax" to specify the number of entries during initialization, and a project attribute, "status"

The unnecessary configuration is also removed during initialization. The configuration is dynamically generated in the program, which increases the flexibility of the program. Let’s analyze it in detail below.

(2), example analysis

(1), first determine what this plug-in does. Let’s take a look at how the plug-in is called and the configuration parameter description. The following code:

Copy code The code is as follows:

{
buttonText: "Add module" ,
Result: [
            {
              text: "Guide Tips",
​​​​​​ url: "help.html",
showClose : "0"
          } ,
            {
             text: "Student Information" ,
​​​​​​ url: "info.html",
             showClose: "1"
          } ,
            {
              text: "Student Classification" ,
   url: "category.html" ,
             showClose: "1"
          } ,
            {
               text: "Big Bear {{bb}}" ,
   url: "bb.html" ,
             showClose: "1"
          } ,
            {
              text: "Beta test module" ,
​​​​​​ url: "test.html",
             showClose: "1"
          } ,
            {
             text: "Three Fatty" ,
​​​​​​ url: "help.html",
             showClose: "1"
          } ,
            {
             text: "Four Bald Men" ,
​​​​​​ url: "help.html",
             showClose: "1"
}
] ,
displayMax : 5 // Maximum displayed items

"bigbear.ui.createTab" contains two parameters, the first is the dom node object, and the second is the plug-in parameter option. "buttonText" represents the text description of the operation button in the "Tab" plug-in.

"result" is an array, which contains the properties of the tab item, including text description, the URL used to make requests when clicking the tab item, "showClose" represents whether the tab option displays a close button.

"status" is also removed during initialization and does not require configuration. The configuration is dynamically generated in the program. There may be a closed state, which are expressed as: 1-default display, 0-closed state, 2-exceeded the default number of entries.

(2), the function is introduced step by step

1---, through optional parameters, initialize the plug-in:

Copy code The code is as follows:

$(function(){
Bigbear.ui.createTab($("#tab"),{
​​​​buttonText: "Add module",
result : [
                {
                 text: "Guide Tips" ,
                   url: "help.html",
showClose : "0"
              },
                {
                 text: "Student Information",
                  url: "info.html",
showClose: "1"
              },
                {
                text: "Student Classification",
                   url: "category.html",
showClose: "1"
              },
                {
                  text: "Big Bear {{bb}}" ,
   url: "bb.html" ,
showClose: "1"
              },
                {
                  text: "Beta test module" ,
                 url: "test.html",
showClose: "1"
              },
                {
                text: "Three Fatty" ,
                   url: "help.html",
showClose: "1"
              },
                {
                                                                                                                                                                                                                                                              text: "Four Bald Men" ,
                   url: "help.html",
showClose: "1"
            }
] ,
          displayMax: 5 // Maximum displayed items
}) ;
}) ;                  

2---, render and complete time binding and related business logic, such as verification of the number of entries during initialization.

Copy code The code is as follows:

tabProto.init = function(){
    if(this._isEmptyResult()){
        this._setContent("暂无任何模块!") ;
    }
    var that = this ;
    this.getElem().find(".title .adder")
    .text(" " this.getOpts()["buttonText"])
    .on("click",function(){
        that.getElem().find(".console-panel").slideToggle(function(){
            that._renderConsolePanel("0") ;
        }) ;
    }) ;
    $.each(this.getOpts()["result"],function(i,item){
        if(that._isDisplayMax(i 1)){
            that._saveOrUpdateStatus(item,"1") ;
        }
        else{
            that._saveOrUpdateStatus(item,"2") ;
        }
        that._render(item) ;
    }) ;
    if(!that._isDisplayMax(this.getOpts()["result"].length)){
        this.getElem().find(".title .more-mod").fadeIn(function(){
            $(this).find(".tag").on("click",function(){
                var root = $(this).next() ;
                root.empty() ;
                $.each(that._getItemListByStatus("2"),function(i,data){
                    $("
").text(data["text"])
                    .on("click",function(){
                        if(that._getItemListByStatus("1").length < that.getOpts()["displayMax"]){
                            that.getElem().find(".title .items div").eq(data["index"]).fadeIn(function(){
                                that._saveOrUpdateStatus(data,"1") ;
                            }) ;
                        }
                        else{
                            alert("不能添加任何模块,目前已经是最大数量!") ;
                        }
                    })
                    .appendTo(root) ;
                }) ;
                root.toggle() ;
            }) ;
           
        });
    }
    this.getElem().find(".title .items div")
    .eq(0)
    .trigger("click") ; // 假定是必须有一项,否则插件意义就不大了!
} ;

3---, tab switching and data content rendering operations.

Copy code The code is as follows:

tabProto._setCurrent = function(index){
var items = this.getElem().find(".title .items div").removeClass("active") ;
items.eq(index).addClass("active") ;
var contents = this.getElem().find(".content .c").hide() ;
contents.eq(index).show() ;
} ;  

Copy code The code is as follows:

item.on("click",function(){
That._setCurrent($(this).index()) ;
That._getContent(data["url"]).done(function(result){
That._setContent(result) ;
})
.fail(function(){
            throw new Error("Net Error !") ;
});
})


Copy code The code is as follows:

tabProto._setContent = function(html){
This.getElem().find(".content").html(html) ;
} ;
tabProto._getContent = function(url){
Return $.ajax({
  url: url
}) ;
} ;

4---, the core auxiliary data operation method, does not involve DOM.

Copy code The code is as follows:

/* update time 2015 1/26 15:36 */
tabProto._isDisplayMax = function(size){
var displayMax = this.getOpts()["displayMax"] || 5 ;
Return (size <= displayMax) ? true : false ;
} ;
tabProto._isEmptyResult = function(){
If(!this.getOpts()["result"].length){
          return false ;
}
Return true ;
} ;
tabProto._saveOrUpdateStatus = function(item,status){
Item["status"] = status ;
} ;
tabProto._getItemListByStatus = function(status){
var list = [] ;
var result = this.getOpts()["result"] ;
$.each(result,function(i,item){
If(status == item["status"]){
              list.push(item);
         }
}) ;
Return list ;
} ;
tabProto._getStatusByIndex = function(index){
var status = null ;
var result = this.getOpts()["result"] ;
$.each(result,function(i,item){
If(index == item["index"]){
status = item["status"] ;
         }
}) ;
Return status ;
} ;

(3), complete code for learning , this code has been tested, including directory structure and related files.

 1,html

Copy code The code is as follows:

 
    

         大熊君{{bb}} - DXJ UI ------ Tab
    

    

        

            

                

                     添加学生信息
                

                

                    
                

                

                    
更多模块

                    

                        
                    

                

            

            

            

            

                
            

        

    

 

2, css

Copy code The code is as follows:

 .dxj-ui-hd {
     padding:0px ;
     margin : 0 auto;
     margin-top:30px;
     width:780px;
     height:60px;
     line-height: 60px;
     background: #3385ff;
     color:#fff;
     font-family: "微软雅黑" ;
     font-size: 28px;
     text-align: center;
     font-weight:bold;
 }
 .dxj-ui-bd {
     padding:0px ;
     margin : 0 auto;
     width:778px;
     padding-top : 30px ;
     padding-bottom : 30px ;
     overflow: hidden;
     border:1px solid #3385ff;
 }
 .dxj-ui-bd #tab {
     padding:0px ;
     margin : 0 auto;
     width:720px;
     overflow: hidden;
     position:relative;
 }
 .dxj-ui-bd #tab .title {
     width:720px;
     overflow: hidden;
     border-bottom:2px solid #3385ff;
 }
 .dxj-ui-bd #tab .title .adder {
     width:160px;
     height:32px;
     line-height: 32px;
     background: #DC143C;
     color:#fff;
     font-family: "微软雅黑" ;
     font-size: 14px;
     text-align: center;
     font-weight:bold;
     float : left;
     cursor:pointer;
 }
 .dxj-ui-bd #tab .title .more-mod {
     overflow:hidden;
     border:1px solid #DC143C;
     width:70px;
     position:absolute;
     right:0;
     margin-right:6px;
     display:none;
 }
 .dxj-ui-bd #tab .title .more-mod .tag{
     height:32px;
     line-height:32px;
     width:70px;
     background: #DC143C;
     color:#fff;
     font-family: arial ;
     font-size: 12px;
     text-align: center;
     cursor:pointer;
 }
 .dxj-ui-bd #tab .title .more-mod .mods {
     overflow:hidden;
     width:70px;
     display:none;
 }
 .dxj-ui-bd #tab .title .more-mod .mods div {
     height:24px;
     line-height:24px;
     width:62px;
     font-family: arial ;
     font-size: 12px;
     cursor:pointer;
     padding-left:10px;
 }
 .dxj-ui-bd #tab .title .items {
     height:32px;
 
     width:480px;
     overflow: hidden;
     float : left;
 }
 .dxj-ui-bd #tab .title .items div {
     padding:0px;
     margin-left:10px;
     width:84px;
     height:32px;
     line-height: 32px;
     background: #3385ff;
     color:#fff;
     font-family: arial ;
     font-size: 12px;
     text-align: center;
     position:relative;
     float : left;
     cursor:pointer;
 }
 .dxj-ui-bd #tab .title .items div span.del {
     width:16px;
     height:16px;
     line-height: 16px;
     display:block;
     background: #DC143C;
     position:absolute;
     right:0 ;
     top:0;
     cursor:pointer;
 }
 .dxj-ui-bd #tab .content {
     width:716px;
     padding-top:30px;
     overflow: hidden;
     border:2px solid #3385ff;
     border-top:0px;
     min-height:130px;
     text-align:center;
 }
 .dxj-ui-bd #tab .content table {
     margin : 0 auto ;
 }
 .dxj-ui-bd #tab .content div.c {
     padding-top : 20px ;
     padding-left:20px;
     background:#eee;
     height:140px;
 }
 .dxj-ui-bd #tab .content div.c .input-content {
     margin-top : 10px ;
     font-family: arial ;
     font-size: 12px;
 }
 .dxj-ui-bd #tab .console-panel {
     width:716px;
     padding-top:20px;
     padding-bottom:20px;
     overflow: hidden;
     border:2px solid #3385ff;
     border-top:0px;
     border-bottom:2px solid #3385ff;
     background:#fff;
     display:none;
 }
 
 .active {
     font-weight:bold ;
 }

3,bigbear.js

复制代码 代码如下:

(function($){
    var win = window ;
    var bb = win.bigbear = win.bigbear || {
        ui : {}
    } ;
    var ui = bb.ui = {} ;
    var Tab = function(elem,opts){
        this.elem = elem ;
        this.opts = opts ;
    } ;
    var tabProto = Tab.prototype ;
    /* update time 2015 1/26 15:36 */
    tabProto._isDisplayMax = function(size){
        var displayMax = this.getOpts()["displayMax"] || 5 ;
        return (size <= displayMax) ? true : false ;
} ;
tabProto._isEmptyResult = function(){
if(!this.getOpts()["result"].length){
return false ;
}
return true ;
} ;
tabProto._saveOrUpdateStatus = function(item,status){
item["status"] = status ;
} ;
tabProto._getItemListByStatus = function(status){
var list = [] ;
var result = this.getOpts()["result"] ;
$.each(result,function(i,item){
if(status == item["status"]){
list.push(item) ;
}
}) ;
return list ;
} ;
tabProto._getStatusByIndex = function(index){
var status = null ;
var result = this.getOpts()["result"] ;
$.each(result,function(i,item){
if(index == item["index"]){
status = item["status"] ;
}
}) ;
return status ;
} ;
tabProto._renderConsolePanel = function(status){
var that = this ;
var root = that.getElem().find(".console-panel") ;
this._resetConsolePanel() ;
$.each(that._getItemListByStatus(status),function(i,item){
var elem = $("
").appendTo(root) ;
            $("")
            .data("item",item)
            .appendTo(elem) ;
            $("").text(item["text"]).appendTo(elem) ;
        }) ;
        if(root.find("div").size()){
            $("")
            .on("click",function(){
                var data = root.find("input[type=radio]:checked").data("item") ;
                if(that._getItemListByStatus("1").length < that.getOpts()["displayMax"]){
                    that.getElem().find(".title .items div").eq(data["index"]).fadeIn(function(){
                        that._saveOrUpdateStatus(data,"1") ;
                    })
                    .trigger("click") ;
                }
                else{
                    that._saveOrUpdateStatus(data,"2") ;
                }
                that.getElem().find(".title .adder").trigger("click") ;
            })
            .appendTo(root) ;
        }
        else{
            root.text("暂无任何可添加的项目!") ;
        }
    } ;
    /* update time 2015 1/26 15:36 */ 
    tabProto._setCurrent = function(index){
        var items = this.getElem().find(".title .items div").removeClass("active") ;
        items.eq(index).addClass("active") ;
        var contents = this.getElem().find(".content .c").hide() ;
        contents.eq(index).show() ;
    } ;
    tabProto.getElem = function(){
        return this.elem ;
    } ;
    tabProto.getOpts = function(){
        return this.opts ;
    } ;
    tabProto._resetContent = function(){
        this.getElem().find(".content").html("") ;
    } ;
    tabProto._setContent = function(html){
        this.getElem().find(".content").html(html) ;
    } ;
    tabProto._getContent = function(url){
        return $.ajax({
            url : url
        }) ;
    } ;
    tabProto._deleteItem = function(elem){
        var that = this ;
        this.getElem().find(".title .items div")
        .eq(elem.index())
        .fadeOut(function(){
            that._resetContent() ;
            that._saveOrUpdateStatus(elem.data("item"),"0") ;
            that._triggerItem(elem.index() + 1) ;
        }) ;
    } ;
    tabProto._triggerItem = function(next){
        var nextStatus = this._getStatusByIndex(next) ;
        var items = this.getElem().find(".title .items div") ;
        next = items.eq(next) ;
        if(next.size() && "1" == nextStatus){ //后继dom节点存在
            next.trigger("click") ;
        }
        else{
            items.eq(0).trigger("click") ;
        }
    } ;
    tabProto._resetConsolePanel = function(){
        this.getElem().find(".console-panel").empty() ;
    } ;
    tabProto.init = function(){
        if(this._isEmptyResult()){
            this._setContent("暂无任何模块!") ;
        }
        var that = this ;
        this.getElem().find(".title .adder")
        .text("+" + this.getOpts()["buttonText"])
        .on("click",function(){
            that.getElem().find(".console-panel").slideToggle(function(){
                that._renderConsolePanel("0") ;
            }) ;
        }) ;
        $.each(this.getOpts()["result"],function(i,item){
            if(that._isDisplayMax(i + 1)){
                that._saveOrUpdateStatus(item,"1") ;
            }
            else{
                that._saveOrUpdateStatus(item,"2") ;
            }
            that._render(item) ;
        }) ;
        if(!that._isDisplayMax(this.getOpts()["result"].length)){
            this.getElem().find(".title .more-mod").fadeIn(function(){
                $(this).find(".tag").on("click",function(){
                    var root = $(this).next() ;
                    root.empty() ;
                    $.each(that._getItemListByStatus("2"),function(i,data){
                        $("
").text(data["text"])
                        .on("click",function(){
                            if(that._getItemListByStatus("1").length < that.getOpts()["displayMax"]){
                                that.getElem().find(".title .items div").eq(data["index"]).fadeIn(function(){
                                    that._saveOrUpdateStatus(data,"1") ;
                                }) ;
                            }
                            else{
                                alert("不能添加任何模块,目前已经是最大数量!") ;
                            }
                        })
                        .appendTo(root) ;
                    }) ;
                    root.toggle() ;
                }) ;
                
            });
        }
        this.getElem().find(".title .items div")
        .eq(0)
        .trigger("click") ; // 假定是必须有一项,否则插件意义就不大了!
    } ;
    tabProto._render = function(data){
        var that = this ;
        var item = $("
").text(data["text"]).appendTo(this.getElem().find(".title .items")) ;
        data["index"] = item.index() ;
        item.on("click",function(){
            that._setCurrent($(this).index()) ;
            that._getContent(data["url"]).done(function(result){
                that._setContent(result) ;
            })
            .fail(function(){
                throw new Error("Net Error !") ;
            });
        })
        .data("item",data) ;
        if("2" == data["status"]){
            item.hide() ;
        }
        if("1" == data["showClose"]){
            $("X")
            .on("click",function(){
                if(win.confirm("是否删除此项?")){
                    that._deleteItem(item) ;
                    return false ; // 阻止冒泡
                }
            })
            .appendTo(item) ;
        }
    } ;
    ui.createTab = function(elem,opts){
        var tab = new Tab(elem,opts) ;
        tab.init() ;
        return tab ;
    } ;   
})(jQuery) ;
  

(四),最后总结

  (1),面向对象的思考方式合理分析功能需求。

  (2),以类的方式来组织我们的插件逻辑。

  (3),不断重构上面的实例,如何进行合理的重构那?不要设计过度,要游刃有余,推荐的方式是过程化设计与面向对象思想设计相结合。

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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Four recommended AI-assisted programming tools Four recommended AI-assisted programming tools Apr 22, 2024 pm 05:34 PM

This AI-assisted programming tool has unearthed a large number of useful AI-assisted programming tools in this stage of rapid AI development. AI-assisted programming tools can improve development efficiency, improve code quality, and reduce bug rates. They are important assistants in the modern software development process. Today Dayao will share with you 4 AI-assisted programming tools (and all support C# language). I hope it will be helpful to everyone. https://github.com/YSGStudyHards/DotNetGuide1.GitHubCopilotGitHubCopilot is an AI coding assistant that helps you write code faster and with less effort, so you can focus more on problem solving and collaboration. Git

Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Apr 07, 2024 am 09:10 AM

On March 3, 2022, less than a month after the birth of the world's first AI programmer Devin, the NLP team of Princeton University developed an open source AI programmer SWE-agent. It leverages the GPT-4 model to automatically resolve issues in GitHub repositories. SWE-agent's performance on the SWE-bench test set is similar to Devin, taking an average of 93 seconds and solving 12.29% of the problems. By interacting with a dedicated terminal, SWE-agent can open and search file contents, use automatic syntax checking, edit specific lines, and write and execute tests. (Note: The above content is a slight adjustment of the original content, but the key information in the original text is retained and does not exceed the specified word limit.) SWE-A

Learn how to develop mobile applications using Go language Learn how to develop mobile applications using Go language Mar 28, 2024 pm 10:00 PM

Go language development mobile application tutorial As the mobile application market continues to boom, more and more developers are beginning to explore how to use Go language to develop mobile applications. As a simple and efficient programming language, Go language has also shown strong potential in mobile application development. This article will introduce in detail how to use Go language to develop mobile applications, and attach specific code examples to help readers get started quickly and start developing their own mobile applications. 1. Preparation Before starting, we need to prepare the development environment and tools. head

Summary of the five most popular Go language libraries: essential tools for development Summary of the five most popular Go language libraries: essential tools for development Feb 22, 2024 pm 02:33 PM

Summary of the five most popular Go language libraries: essential tools for development, requiring specific code examples. Since its birth, the Go language has received widespread attention and application. As an emerging efficient and concise programming language, Go's rapid development is inseparable from the support of rich open source libraries. This article will introduce the five most popular Go language libraries. These libraries play a vital role in Go development and provide developers with powerful functions and a convenient development experience. At the same time, in order to better understand the uses and functions of these libraries, we will explain them with specific code examples.

Which Linux distribution is best for Android development? Which Linux distribution is best for Android development? Mar 14, 2024 pm 12:30 PM

Android development is a busy and exciting job, and choosing a suitable Linux distribution for development is particularly important. Among the many Linux distributions, which one is most suitable for Android development? This article will explore this issue from several aspects and give specific code examples. First, let’s take a look at several currently popular Linux distributions: Ubuntu, Fedora, Debian, CentOS, etc. They all have their own advantages and characteristics.

Understanding VSCode: What is this tool used for? Understanding VSCode: What is this tool used for? Mar 25, 2024 pm 03:06 PM

&quot;Understanding VSCode: What is this tool used for?&quot; 》As a programmer, whether you are a beginner or an experienced developer, you cannot do without the use of code editing tools. Among many editing tools, Visual Studio Code (VSCode for short) is very popular among developers as an open source, lightweight, and powerful code editor. So, what exactly is VSCode used for? This article will delve into the functions and uses of VSCode and provide specific code examples to help readers

Is PHP front-end or back-end in web development? Is PHP front-end or back-end in web development? Mar 24, 2024 pm 02:18 PM

PHP belongs to the backend in web development. PHP is a server-side scripting language, mainly used to process server-side logic and generate dynamic web content. Compared with front-end technology, PHP is more used for back-end operations such as interacting with databases, processing user requests, and generating page content. Next, specific code examples will be used to illustrate the application of PHP in back-end development. First, let's look at a simple PHP code example for connecting to a database and querying data:

Exploring Go language front-end technology: a new vision for front-end development Exploring Go language front-end technology: a new vision for front-end development Mar 28, 2024 pm 01:06 PM

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

See all articles