xuyuan923 / learn-kissy Goto Github PK
View Code? Open in Web Editor NEWkissy学习片段
kissy学习片段
<p>
<button>点击我试试</button>
添加一个段落
</p>
点击button,因为事件向上冒泡,会触发p的click事件.
$('button').on('click',function(ev){
ev.stopPropagation();
})
阻止p的click事件。
halt() 的作用是停止事件冒泡,同时停止默认行为,比如a标签的跳转、button的提交等。
阻止事件的默认行为,如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']
}
});
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指向event绑定的事件的节点
currentTarget指向实际的事件源
<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'));
})
详情看api
Anim (elem, props[, duration, easing, completeFn])
默认为 ‘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]之间)”.
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("动画结束!")
})
有时我们需要获取用户按下的键码来做些过滤处理:
$('.J_Input').on('keyup',function(ev){
var code = ev.which;
//空格键
if(code === 32){
//...
}
})
使用which属性即可获取到键码.
<body>
<p>添加一个段落</p>
</body>
$( "body" ).delegate( "click","p", function(ev) {
// this指向受理委托的父节点,这里为p的父节点body
$(this).append( "<p>添加一个段落</p>" );
});
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)
});
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('这是个提示');
})
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模块继承promise.
.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;
});
.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();
$('.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'
});
表单元素会带有默认事件,常用的有:
kissy没有jQuery触发这些事件的门面方法,比如$('input').blur(),但可以通过fire()方法来触发表单事件,比如:$('input').fire('blur')
width() 与 height() 返回元素宽度与高度的数值,不包含 padding, border, margin
innerWidth() 算值时会把左右 padding 值加上,innerHeight() 算值时会把上下 padding 值加上
outerWidth() 与 outerHeight() 比较特殊,默认算值时只会把 border 加上,如果希望加上 margin 值,需要传递个 true 参数值。
<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.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() 静态方法:
var Tip = Base.extend({
//向类注入个show方法
show: function(){
}
});
Base.extend() 非常强大,支持多层继承:
var Tip2 = Base.extend(Tip,{
hide: function(){
}
});
Tip2 将拥有show()与hide()二个方法。
如何让组件逻辑,在 new 初始化时就执行呢?
var Tip = Base.extend({
//new 初始化时就会执行
initializer:function(){
var self = this;
alert(2);
}
});
既然有初始化函数,自然有对应的析构函数
var Tip = Base.extend({
destructor:function(){
var self = this;
self.set('isRender',false);
}
});
析构函数会在 tip.destroy() 后执行,destroy是Base注入的析构方法。
destructor() 不是必须的。
//定义模块
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常用的事件有:
我们常有如下需求:
页面中存在多个异步请求,它们的loading状态处理逻辑是一样的,请求中出现“正在加载中...”提示,请求完成,隐藏提示。
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请求都有效,是全局性的事件。
Defer()
方法用于控制对应promise传递的成功和失败promise
属性是用于外部监听,传递成功/失败的函数resolve()
向事务传值,并触发事务执行//实例化一个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可以帮助你阻塞地加载所有依赖的样式,这样我们就可以在head部分优先加载样式,就不会出现上文提到的样式变化问题。
<script src="http://g.tbcdn.cn/kissy/k/1.4.8/??seed-min.js,import-style-min.js"></script>
<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文件。
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.add(
'模块名/路径',
['依赖的模块'],
function(S,require, exports, module){
//模块回调函数(在依赖模块加载完成后执行)
})
第一个参数模块名/路径
,第二个参数依赖的模块
均为gulp-kmc自动生成,不能手动配置。
留意:函数第一个参数永远是S(KISSY变量)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.