search
HomeWeb Front-endJS TutorialJavaScript plug-in development tutorial (4)_javascript skills

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.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 } ;
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     } ;
    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.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.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
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
JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

See all articles

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use