借点击和轻触来研究节点门面和自定义事件
当支持轻触时用轻触,否则使用点击
// 初始版本
// 使用自定义事件增加 tap 和tapend 事件
// 当支持轻触是用轻触 ,否则用点击
function addTapListener(node, callback) {
//start by supporting mousevents
var startEvent = 'mousedown', endEvent = 'mouseup';
//if touch events are available use them instead
if (typeof(window.ontouchstart) != 'undefined') {
//touch events work
startEvent = 'touchstart';
endEvent = 'touchend';
}
//添加自定义事件 tap, 后续可以像绑定click事件一样绑定
node.addEventListener(startEvent, function(e) {
var tap = document.createEvent('CustomEvent');
tap.initCustomEvent('tap', true, true, null);
node.dispatchEvent(tap);
});
//添加自定义事件 tapend, 后续可以像绑定click事件一样绑定
node.addEventListener(endEvent, function(e) {
var tapend = document.createEvent('CustomEvent');
tapend.initCustomEvent('tapend', true, true, null);
node.dispatchEvent(tapend);
})
//绑定 tap 事件
node.addEventListener('tap', callback);
}
//调用addTapListener 方法 添加tap 和 tapend事件
addTapListener(document.getElementById('toggle'), function(e){
e.preventDefault();
e.target.className = 'active button';
togglePicture();
});
//给元素添加tapend事件
node.addEventListener('tapend', function(e){
e.preventDefault();
e.target.className = "button";
});
//
//优化版本 使用节点门面
(function(){
var TOUCHSTART, TOUCHEND;
//normal touch events
if (typeof(window.ontouchstart) != 'undefined') {
TOUCHSTART = 'touchstart';
TOUCHEND = 'touchend';
//microsoft touch events
} else if (typeof(window.onmspointerdown) != 'undefined') {
TOUCHSTART = 'MSPointerDown';
TOUCHEND = 'MSPointerUp';
} else {
TOUCHSTART = 'mousedown';
TOUCHEND = 'mouseup';
}
function NodeFacade(node){
this._node = node;
}
NodeFacade.prototype.getDomNode = function() {
return this._node;
}
//使用原型 绑定on方法
NodeFacade.prototype.on = function(evt, callback) {
if (evt === 'tap') {
this._node.addEventListener(TOUCHSTART, callback);
} else if (evt === 'tapend') {
this._node.addEventListener(TOUCHEND, callback);
} else {
this._node.addEventListener(evt, callback);
}
return this;
}
//使用原型 绑定off方法
NodeFacade.prototype.off = function(evt, callback) {
if (evt === 'tap') {
this._node.removeEventListener(TOUCHSTART, callback);
} else if (evt === 'tapend') {
this._node.removeEventListener(TOUCHEND, callback);
} else {
this._node.removeEventListener(evt, callback);
}
return this;
}
//使用门面模式,模拟jquery的写法
window.$ = function(selector) {
var node = document.querySelector(selector);
if(node) {
return new NodeFacade(node);
} else {
return null;
}
}
})();
//链式绑定
$('.button').on('tap', function(e) {
e.preventDefault();
togglePicture();
e.target.className = "active button";
}).on('tapend', function(e) {
e.target.className = "button";
});