关于组件 (不定时更新)

1.组件的定义和加载

tabview.css

.menu{}

.content{}

tabview.js

var abc=5;
function TabView(cfg){
    this.a=cfg.a;
    this.b=cfg.b;
}
TabView.prototype={
    c:function(){ abc++ },
    d:function(){ abc-- }
}

tabview.html

<head>
    <link rel="stylesheet" href="tabview.css">
</head>
<body>
    <script src='tabview.js'></script>
    <script>
        (function(){
            var tabView=new TabView();
        })();
    </script>
</body>

2.css命名空间和js匿名空间,防止css和js的命名冲突

①css通过加前缀形成命名空间

tabview.css

.tabview_menu{}

.tabview_ content{}

 treeview.css

.treeview_menu{}

.treeview_ content{}

②js通过匿名空间隔开公有私有(闭包)

tabview.js

(function(){
    var abc=5;
    function TabView(cfg){
        this.a=cfg.a;
        this.b=cfg.b;
    }
    TabView.prototype={
        c:function(){ abc++ },
        d:function(){ abc-- }
    }
    window.TabView=TabView;
})();

treeview.js

(function(){
    var abc=100;
    function TreeView(cfg){
        this.a=cfg.a;
        this.b=cfg.b;
    }
    TreeView.prototype={
        c:function(){ abc*=2 },
        d:function(){ abc/=2 }
    }
    window.TreeView=TreeView;
})();

3.组件的依赖关系

①增加一个有依赖关系的组件

<head>
    <link rel="stylesheet" href="animate.js">
    <link rel="stylesheet" href="tabview.js">
    <link rel="stylesheet" href="treeview.js">
</head>
<body>
    <script src='tabview.js'></script>
    <script>
        (function(){
            var tabView=new TabView({
                animate: new Animate()
            });
        })();
    </script>
</body>

问题:

1.需手动处理组件间的依赖关系

2.加载项太多,破坏页面的整洁度

②模块化和require.js

define定义模块

mode1.js

define(function(){
    return { a:3 };
});

mode2.js

define( [ 'mode1' ],function( m1 ){
    var a,b=2,c=3;
    a=c*m1.a;
    return{
        a: a
        b: b
    };
});

main.js

require( [ 'mode2' ],function(m2){
    alert( m2.a*m2.b );
});

index.html

<body>
    <script src='js/require.js' data-main='js/main'></script>
</body>
原文地址:https://www.cnblogs.com/kanghaiwei/p/6290925.html