Friday, February 8, 2013

MSPointers and multi-touch implementation

I've recently talked with Jeff Burtoft from Microsoft about the new Pointer proposal. In short, you needn't concern yourself with input type, e.i. mouse, touch ect. Just use addEventListener("MSPointerMove",... and you'll get all events.

My concern was that in multi touch scenarios, whatever function you register, will be fired thousands of times multiplied with number of fingers touching the screen. In a single threaded environment like JavaScript, this spells disaster.

But then he came up with this excellent explanation to how you would implement this and an example.
As for the methods that are attached to those events, just as you do when you are using touchmove on iOS, you need to be cautions as to the actions you are trying to perform, since the do fire thousands of time a second.  When I build an app that is tracking touches on a screen, instead of having the pointermove event fire a series of methods, I simply have it update an array of finger positions.   I then go to my draw method (usually with requestanimationframe) and then animate based on the array.
You can see based on the code example I used:
Having this mediator between the input and the behavior is a strike of genius. How many times have you been struggling with queued events? No more, just have the mediator handle the execution.

Actually this is a pattern I've implemented before but for some reason tend to forget. And I have developed code in production, that does something like:
function foo(){
  foo.isAnimating = foo.isAnimating || false;
  if(!foo.isAnimating) {
    foo.isAnimating = true;
    // do stuff..

Now, that I wrote it down, I just hope the mediator pattern will stick!

1 comment:

Unknown said...

Thanks Jon for putting this up. I want to make sure I give credit where credit is due. I didn't come up with this concept, I learned it from looking at code written by some of our JS gurus here at Microsoft.
It does solve the issue you brought up. You don't want to be afraid to let users touch with all 10 fingers if they want! thanks for the write up and analysis..Jeff