Binding two actions to the same event
I would like to bind two events together.
Right now my set up is I bind all mouse actions that I need to a canvas then call a wrapper function that makes mouse position relative to the canvas. The wrapper function then calls the correct action in an internal function. I would also like to bind the touchstart
touchmove
and touchend
Here is an example structure of what I have:
$('canvas').bind('mousedown mousemove mouseup', ev_canvas);
function ev_canvas (e)开发者_如何学C {
var pos = findPos(this);
e._x = e.pageX - pos.x;
e._y = e.pageY - pos.y;
var func = tool[e.type];
if (func) {
func(e);
}
}
tools.pen = function () {
tool.mousedown = function (e) {
//Stuff to do
};
tool.mousemove = function (e) {
//Stuff to do
};
tool.mouseup = function (e) {
//Stuff to do
};
}
This calls the correct tool and then calls the mouse(up|down|move) function depending on the action.
Is there a way to bind the touch actions to those so it can call one or the other with out copy and pasting a bunch of code?
I would create a mapping table - eventName : callbackName. Here is a sample
var functionMappings = {
mousemove: "mousemove",
touchmove: "mousemove",
mousedown: "mousedown",
touchstart: "mousedown",
mouseup: "mouseup",
touchend: "mouseup"
};
var func = tool[functionMappings[e.type]];
if (func) {
func(e);
}
精彩评论