Giter Site home page Giter Site logo

learn-kissy's People

Contributors

xuyuan923 avatar

Watchers

 avatar

learn-kissy's Issues

stopPropagation()与halt()与preventDefault()区别

事件冒泡概念

<p>
    <button>点击我试试</button>
    添加一个段落
</p>

点击button,因为事件向上冒泡,会触发p的click事件.

stopPropagation()阻止事件冒泡

$('button').on('click',function(ev){
    ev.stopPropagation();
})

阻止p的click事件。

halt()

halt() 的作用是停止事件冒泡,同时停止默认行为,比如a标签的跳转、button的提交等。

preventDefault()

阻止事件的默认行为,如a标签的跳转、button的提交等。

可以得出这样的总结:halt() = stopPropagation() + preventDefault()

使用别名机制维护公共模块版本

比如 bee-demo 项目中引用了二个组件,组件的模块名称中包含版本号信息,像kg/offline/2.0.0/index,但我们不希望在业务模块 require 时带有版本号,require('kg/offline/index')可以如下配置:

KISSY.config('modules',{
    'kg/offline/index':{
        alias:['kg/offline/2.0.0/index']
    },
    'kg/auth/index':{
        alias:['kg/auth/2.0.0/index']
    }
});

demo

KISSY.config('modules',{
    'bee-demo/b':{
        alias:['bee-demo/a']
    }
});

KISSY.add('bee-demo/a',function(S ,require, exports, module){
    var Node = require('node');
    Node.all('body').html('bee-demo/b 等价于 bee-demo/a');
});
KISSY.use('bee-demo/b');

target与currentTarget

target

target指向event绑定的事件的节点

currentTarget

currentTarget指向实际的事件源

demo

<div class="J_Target">
    <button class="J_CurrentTarget">target</button>
    点我试试
</div>
$('.J_Target').on('click',function(ev){
    //ev.target 指向被点击的节点
    // 实际click的元素是button.J_CurrentTarget
    var $target = $(ev.target); //=>$('.J_CurrentTarget')
    // 事件源是$('.J_Target')
    var $currentTarget = $(ev.currentTarget); //=>$('.J_Target')
    $('.J_TargetText').text('target:'+$target.attr('class'));
    $('.J_CurrentTargetText').text('currentTarget:'+$currentTarget.attr('class'));
})

anim动画

详情看api

Anim (elem, props[, duration, easing, completeFn])

easing (String)

默认为 ‘easeNone’ , 动画平滑函数, 可取值 “swing”, “easeNone”, “linear”, “easeIn”, “easeOut”, “easeBoth”,”easeInStrong”, “easeOutStrong”,”easeBothStrong”,”elasticIn”,”elasticOut”, “elasticBoth”,”backIn”,”backOut”,”backBoth”, “bounceIn”,”bounceOut”,”bounceBoth”, “cubic-bezier(p1x, p1y, p2x, p2y)(所有取值必须在[0,1]之间)”.

demo

var Node = require('node');
var $ = Node.all;
$('.J_AnimDiv').animate({
    'background-color':'#fcc',
    'border': '5px dashed #999',
    'width': '200px',
    'height': '30px',
    'left': '400px',
    'top': '285px',
    'opacity': '.5',
    'font-size': '20px',
    'padding': '30px 0',
    'color': '#FF3333'
},2,
'bounceOut',function(){
    $('body').append("动画结束!")
})

键盘事件获取键码

有时我们需要获取用户按下的键码来做些过滤处理:

获取键码 which

$('.J_Input').on('keyup',function(ev){
    var code = ev.which;
    //空格键
    if(code === 32){
        //...        
    }
})

使用which属性即可获取到键码.

事件代理

delegate(eventType,selector,handler)

<body>
    <p>添加一个段落</p>
</body>
$( "body" ).delegate( "click","p", function(ev) {
    // this指向受理委托的父节点,这里为p的父节点body
    $(this).append( "<p>添加一个段落</p>" );
});

Base.extend()添加自定义事件

Base拥有Event.Target的所有特性。

show:function(msg){
    var self = this;
    //...

    self.fire('show',{msg: msg});
}

this.fire('show',{msg: msg}) 广播一个show事件,将msg内容传递出去。
外部监听:

var tip = new Tip();
tip.on('show',function(ev){
    $('body').append('show事件:' + ev.msg)
});

demo

KISSY.add('tip',function(S ,require, exports, module){
        var Base = require('base');
        var Node = require('node');
        var $ = Node.all;

        var Tip = Base.extend({
            //初始化
            initializer:function(){
                var self = this;
                var $target = self.get('$target');
            },
            //显示提示层
            show:function(msg){
                var self = this;
                var tpl = self.get('tpl');
                var html = S.substitute(tpl,{text:msg});
                var $el = $(html).appendTo('body');
                self.set('$target',$el);
                S.later(function(){
                    $el.addClass('tip-show');
                });
                self.set('visible',true);
                S.later(function(){
                    self.set('visible',false);
                },2000);
                self.fire('show',{msg: msg});
            }
        },{
            ATTRS:{
                $target:{
                    value:'',
                    getter:function(v){
                        return $(v);
                    }
                },
                tpl:{
                    value: '<div class="tip J_Tip"><div class="tip-content"><span>{text}</span></div></div>'
                },
                visible:{
                    value: false,
                    setter: function(v){
                        var self = this;
                        var $target = self.get('$target');
                        if(!v){
                            $target.removeClass('tip-show');
                        }else{
                            S.later(function(){
                                $target.addClass('tip-show');
                            });
                        }
                        return v;
                    }
                }
            }
        },'Tip');
        module.exports = Tip;
    });
    //使用模块
    KISSY.use('tip,node',function(S,Tip,Node){
        var $ = Node.all;
        var tip = new Tip();
        tip.on('show',function(ev){
            $('body').append('show事件:' + ev.msg)
        });
        tip.show('这是个提示');
    })

KISSY选择器

Node.all()获取的是节点集合
Node.one()获取第一个节点

子孙选择器

<div class="J_Parent">
    <span class="J_Child"></span>
</div>

获取 .J_Parent 节点下的 .J_Child 节点:

var $child = $(".J_Parent .J_Child");

只想获取子节点

var $child = $(".J_Parent > .J_Child");

从多个子孙节点精确选取

<ul class="J_Parent">
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>

如何获取第一个 li 节点呢?

var $first = $(".J_Parent > li:first-child");

如何获取指定索引的 li 节点呢?=>item()

var $two = $(".J_Parent > li").item(2);

如何获取最后一个 li 节点呢?

var $last = $(".J_Parent > li:last-child");

相邻兄弟选择器

<p class="J_Brother">阿大</p>
<p>阿二</p>

我们要获取阿二节点:

var $p = $('.J_Brother + p');

通过 “+” 号即可。

伪类选择器

<input type="checkbox" value="javascript" class="J_Checkbox" checked> javascript
<input type="checkbox" value="html" class="J_Checkbox" disabled> html

要选取被选中的复选框节点:

var $checkbox = $('.J_Checkbox:checked');

如何获取被禁用的节点呢:

var $disabled = $('.J_Checkbox:disabled');

非选择器

<p class="J_Brother">阿大</p>
<p>阿二</p>

我们要通过非的方式获取阿二节点:

var $p = $('p:not(.J_Brother)');

使用 :not(selector) 即可。

节点添加到容器

var $html = $('<div>我是新节点</div>');
$('.J_Wrapper').append($html);

可以通过 $('html片段'),将html片段转成NodeList

io模块使用

io模块继承promise.

对于get请求

对于data类型为jsonp的数据使用.jsonp()

io({
    type:"get",
    dataType: "jsonp",
    url: 'https://api.github.com/repos/minghe/auth',
    data: {},
    success: function(authData){
         $('body').append('<p>'+authData.name+':'+authData.description+'</p>');
     }
});

等价于

io.jsonp('https://api.github.com/repos/minghe/auth').then(function(result){
    var authData = result[0].data;
    $('body').append('<p>'+authData.name+':'+authData.description+'</p>');
    return data;
});

对于data类型为json的数据使用.getJSON()

var io = require('io');

io.getJSON('2.json').then(function(result){
    var data = result[0];
    $('body').append('<p>'+data.name+'来自'+data.location+'</p><p><img src="'+data.avatar_url+'" width="50"></p>');
    return data;
});

getJSON() 等价于:

io({
    type:"get",
    url: url,
    dataType: "json"
}).then();

对于post请求

$('.J_Submit').on('click',function(ev){
    ev.halt();
    io.post('3.json',{
        user: $('.J_User').val(),
        email: $('.J_Email').val()
    },'json').then(function(result){
        var data = result[0];
        if(data.success){
            $('body').html('异步post数据成功!');
        }
    })
})

等价于:

io({
    type:"post",
    url: '3.json',
    data: data,
    dataType: 'json'
});

用fire()触发表单事件

表单元素会带有默认事件,常用的有:

  • submit:表单提交事件
  • blur:失去焦点事件
  • focus:获得焦点事件
  • change:值改变触发的事件,常用于选择框
  • select:比如输入框选中文字后触发

kissy没有jQuery触发这些事件的门面方法,比如$('input').blur(),但可以通过fire()方法来触发表单事件,比如:$('input').fire('blur')

获取/设置宽度与高度

width()与height()

width() 与 height() 返回元素宽度与高度的数值,不包含 padding, border, margin

innerWidth() 与 innerHeight()

innerWidth() 算值时会把左右 padding 值加上,innerHeight() 算值时会把上下 padding 值加上

outerWidth() 与 outerHeight()

outerWidth() 与 outerHeight() 比较特殊,默认算值时只会把 border 加上,如果希望加上 margin 值,需要传递个 true 参数值。

demo

<div class="J_Size_1" style="width:200px;height:200px;padding:10px;margin:20px;background-color: #33be40;border:1px solid #00334d;">
    这是一个设置宽度与高度的容器
</div>
var $div = $('.J_Size_1');
var width = $div.width(); //200
var height = $div.height(); //200
var innerWidth = $div.innerWidth(); //220
var innerHeight = $div.innerHeight(); //220
var outerWidth = $div.outerWidth(true); //262
var outerHeight = $div.outerHeight(true); //262

KISSY的模块系统

使用KISSY.add()包裹模块,支持commonjs风格

    //定义一个模块
    KISSY.add('demo-mod',function(S,require,exports,module){
        var Node = require('node');
        var $ = Node.all;
        exports.test = function () {
            $('body').html('CommonJs');
        };
    });
    //使用模块
    KISSY.use('demo-mod',function(S,demo){
        demo.test();
    })

理解base模块

所有业务模块都建议继承于base.

Base.extend()强大的继承

类想要继承于Base,非常简单,只需要使用 Base.extend() 静态方法:

var Tip = Base.extend({
    //向类注入个show方法
    show: function(){

    }
});

Base.extend() 非常强大,支持多层继承:

var Tip2 = Base.extend(Tip,{
    hide: function(){

    }
});

Tip2 将拥有show()与hide()二个方法。

initializer() 默认类初始化函数

如何让组件逻辑,在 new 初始化时就执行呢?

var Tip = Base.extend({
    //new 初始化时就会执行
    initializer:function(){
        var self = this;
        alert(2);
    }
});

destructor() 析构函数

既然有初始化函数,自然有对应的析构函数

var Tip = Base.extend({
    destructor:function(){
        var self = this;
        self.set('isRender',false);
    }
});

析构函数会在 tip.destroy() 后执行,destroy是Base注入的析构方法。
destructor() 不是必须的。

demo

//定义模块
KISSY.add('tip',function(S,require,exports,module){
        var Base = require('base');
        var Node = require('node');
        var $ = Node.all;

        var Tip = Base.extend({
            //初始化
            // 当使用new Tip()时,initializer就被执行
            initializer:function(){
                var self = this;
                var $target = self.get('$target');
            },
            //显示提示层
            show:function(msg){
                var self = this;
                var tpl = self.get('tpl');
                var html = S.substitute(tpl,{text:msg});
                var $el = $(html).appendTo('body');
                S.later(function(){
                    $el.addClass('tip-show');
                });
                S.later(function(){
                    $el.removeClass('tip-show');
                },2000);
            }
        },{
            ATTRS:{
                $target:{
                    value:'body',
                    getter:function(v){
                        return $(v);
                    }
                },
                tpl:{
                    value: '<div class="tip J_Tip"><div class="tip-content"><span>{text}</span></div></div>'
                }
            }
        },'Tip');
        module.exports = Tip;
})
//使用模块
//将上述定义的模块暴露出来,作为使用的方法
KISSY.use('tip',function(S,Tip){
        var tip = new Tip();
        tip.show('这是个提示');
    })

添加节点

对于下面的dom结构:

<p id="J_One">这是第一个节点</p>
<p id="J_Two">这是第二个节点</p>

实现这样的需求:将第二个节点放在第一个节点前面

方法一:

//返回的是指定节点$('#J_One')
$('#J_One').before($('#J_Two'))

方法二:

//返回的是要插入的节点$('#J_Two')
$('#J_Two').insertBefore($('#J_One')).text('我是第二个节点,但我要当第一个');

io请求提示事件

io常用的事件有:

  • send 事件:请求发送前触发
  • complete 事件:请求完成后触发(不管是请求失败还是成功都会触发)
  • success 事件:请求成功后触发
  • error 事件:请求失败后触发

我们常有如下需求:
页面中存在多个异步请求,它们的loading状态处理逻辑是一样的,请求中出现“正在加载中...”提示,请求完成,隐藏提示。

demo

var io = require('io');
    //请求发送前触发
    io.on('send',function(){
        $('.J_Loading').addClass('tip-show');
    });
    //请求完成后触发
    io.on('complete',function(){
        $('.J_Loading').removeClass('tip-show');
    });

PS: io的事件对所有io请求都有效,是全局性的事件。

promise模块

方法

  • Defer()方法用于控制对应promise传递的成功和失败
  • promise属性是用于外部监听,传递成功/失败的函数
  • resolve()向事务传值,并触发事务执行

demo

//实例化一个Defer,不用实例化Promise
//Defer用于控制对应promise传递的成功和失败
var d = new Promise.Defer();
//promise是Defer的核心属性, 用于外部监听,传递成功/失败的函数
var promise = d.promise;
//then方法第一个参数监听事务成功流转到此的值,返回新的promise,并向下传递
promise.then(function (v) {
    return v + 1;
}).then(function (v) {
    $('body').append('<p>值为:<span style="color:red">'+v+'</span>,第二个then的v为第一个then中success回调的返回值。</p>');
});
//向事务传值,并触发事务执行
d.resolve(1);

使用importStyle优先加载css或js

importStyle可以帮助你阻塞地加载所有依赖的样式,这样我们就可以在head部分优先加载样式,就不会出现上文提到的样式变化问题。

需要使用 import-style 模块

<script src="http://g.tbcdn.cn/kissy/k/1.4.8/??seed-min.js,import-style-min.js"></script>

加载css

<head>
    <!-- 引入seed和import-style -->
    <script src="http://g.tbcdn.cn/kissy/k/1.4.8/??seed-min.js,import-style-min.js"></script>
    <!-- 配置模块 -->
    <script>
    KISSY.config({
        packages: [
            {
                name: 'bee-demo',
                base: 'http://demo.apebook.org/bee-demo/build',
                ignorePackageNameInUri: true
            }
        ]}
    );
    </script>
    <!--引入样式-->
    <script>
        KISSY.importStyle('bee-demo/index.css');
    </script>
</head>

模块css的模块名最好加上.css后缀,不然如果同时存在index.js和index.css时,KISSY.importStyle('bee-demo/index') 会优先加载js文件。

使用依赖表控制combo

demo

KISSY.config('modules',{
        'kg/offline/2.0.0/index':{
            //定义了 offline 模块依赖于 auth 模块
            //相关于告诉 kissy ,我们要把这二个组件combo到一块
            //等价于??kg/offline/2.0.0/index,kg/auth/2.0.0/index
            requires:['kg/auth/2.0.0/index']
        }
    });

    KISSY.use('kg/offline/2.0.0/index',function(s,Offline){
        //use 表单校验组件
        KISSY.use('kg/auth/2.0.0/index');
    });

KISSY模块规范

KISSY.add(
    '模块名/路径',
    ['依赖的模块'],
    function(S,require, exports, module){
      //模块回调函数(在依赖模块加载完成后执行)
})

第一个参数模块名/路径,第二个参数依赖的模块均为gulp-kmc自动生成,不能手动配置。

模块回调函数 参数的含义

留意:函数第一个参数永远是S(KISSY变量)

  • require 为加载依赖模块函数,比如 var Node = require('node');
  • exports 类似NodeJs的exports方法,导出(暴露)接口供外部使用
  • module.exports 类似NodeJs的module.exports,用于导出(暴露)接口供外部使用

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.