1

I've bound mousemove of my app to check if the user is still using it:

<body data-ng-mousemove="data.OnMouseMove()"  

where my controller does this:

$scope.data.OnMouseMove = function ()
{
    AccountService.RefreshToken();
};

This works fine but breaks animations if the user continuously moves the mouse. So I want to disable the mousemove event for 20 seconds but don't know how to. Something like this pseudocode:

$scope.data.OnMouseMove = function ()
{
    document.getElementsByTagName("body")[0].data-ng-mousemove = "";

    AccountService.RefreshToken();

    window.setTimeout(function () 
    {
       document.getElementsByTagName("body")[0].data-ng-mousemove = "data.OnMouseMove()";
    }, 20000);
};
Richard
  • 14,798
  • 21
  • 70
  • 103
  • Have you considered putting ```AccountService.RefreshToken();``` inside the "setTimeout" callback body? –  Aug 26 '15 at 08:13
  • 1
    Alternatively, you might be interested in this: http://stackoverflow.com/questions/18240168/genuinely-stop-a-element-from-binding-unbind-an-element-angularjs –  Aug 26 '15 at 08:14
  • Maybe you want to [debounce](http://underscorejs.org/#debounce) your mouse move handler? – Tomislav Dyulgerov Aug 26 '15 at 08:21
  • Thanks all, yes, my refresh token method is throttled and takes almost 0 milliseconds. But just having the mousemove event on the body causes this event to trigger constantly. I need to actually completely unbind and later rebind the event, not just do less in it. Checking out Sphaso's link now... – Richard Aug 26 '15 at 08:25

2 Answers2

0

Maybe you can have a flag in your service if the token has been recently refreshed. If that's the case then just return void in your mouse over event.

Jayson
  • 157
  • 1
  • 10
0

I can't find any way of dynamically changing the ng-mousemove event. AngularJS is just not designed that way.

The only other AngularJS option might be to write a custom attribute directive and dynamically use $compile and $destroy to change it. But I don't know enough to do that.

The simplest and fastest solution is simply to use a non-Angular Javascript event that you can easily bind and unbind, and in that event call the Angular service.

Like so:

"use strict";

var HandleMouseMoveOnBody = function()
{
    var htmlScope = angular.element(document.getElementById('htmlId')).scope(); //get access to angular from the outside
    htmlScope.data.OnMouseMove(); //refresh the token in Angular service

    $('body').off('mousemove'); //stop watching mouse movement as it slows the entire page

    //watch mouse movement again in a minute
    window.setTimeout(function() 
    {
        $('body').on('mousemove',  HandleMouseMoveOnBody);
    },  55000);        
};

//start watching
$(document).ready(function()
{
    $('body').on('mousemove', HandleMouseMoveOnBody);
});
Richard
  • 14,798
  • 21
  • 70
  • 103