//directive.js
import Vue from 'vue'
/*touch事件*/
Vue.directive('touch',{
isTap: function(tapObj){
let isTap = Math.abs(tapObj.pagX-tapObj.endX) > 10 || Math.abs(tapObj.pagY-tapObj.endY) > 10;
let _x = tapObj.pagX-tapObj.endX;
let _y = tapObj.pagY-tapObj.endY;
let ads = Math.abs(_x)-Math.abs(_y)
if(_x > 10 && ads>0)
this.tapObj.direction = 'left'
if(_x < -10 && ads>0)
this.tapObj.direction = 'right'
if(tapObj.pagY-tapObj.endY > 10 && ads<0)
this.tapObj.direction = 'up'
if(tapObj.pagY-tapObj.endY < -10 && ads<0)
this.tapObj.direction = 'down'
return isTap;
},
update: function (fn) {
var me = this;
me.tapObj = {};
me.touches = [];
if(typeof fn !== 'function')
return console.error('The param of directive "v-touch" must be a function!');
me.handler = (e) => {
e.tapObj = me.tapObj;
fn.call(self,e);
}
this.el.addEventListener('touchstart',function(event){
me.touches = [];
let touches = event.touches[0];
me.touches.push(touches);
me.tapObj.pagX = touches.pageX;
me.tapObj.pagY = touches.pageY;
me.tapObj.clientX = touches.clientX;
me.tapObj.clientY = touches.clientY;
},false)
let movehandler = function(event){
this.touches.push(event.touches[0]);
let objStar = this.touches[0];
let objEnd = event.touches[0];
if(Math.abs(objStar.clientX - objEnd.clientX) > Math.abs(objStar.clientY - objEnd.clientY)){
event.preventDefault();
}
}
this.el.addEventListener('touchmove',movehandler.bind(this),false)
this.el.addEventListener('touchend',function(event){
if(me.touches.length>1){
let touches = me.touches.pop();
me.tapObj.endX = touches.pageX;
me.tapObj.endY = touches.pageY;
me.tapObj.clientEndX = touches.clientEndX;
me.tapObj.clientEndY = touches.clientEndY;
if (me.isTap(me.tapObj))
me.handler(event);
}
me.el.removeEventListener('touchmove',movehandler,false)
},false)
}
})
/*監聽貼上事件*/
Vue.directive('paste',{
update: function (fn) {
let me = this;
if(typeof fn !== 'function')
return console.error('The param of directive "v-parse" must be a function!');
me.handler = () => {
fn.call();
}
this.el.addEventListener('paste',function(event){
me.handler()
})
}
})