Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call foo only if click OR focus fired

I have a directive in which I bind focus and click events to element:

app.directive('mydirective', function () {
  return {
    link: function ($scope, $element, $attrs) {
      $element.bind('click focus', function (e) {
        foo(e);
      });
    }
  };
});

I want to call foo once if focus or click event fired. But when clicking on element, focus event gets fired and foo gets called twice. how to prevent calling foo for the second time?

Edit: Yes. I wasn't a good idea to mix hover with click and focus. Thanks every body

like image 356
Reyraa Avatar asked Dec 15 '14 12:12

Reyraa


2 Answers

You can debounce the events, that would only fire the function for the first event

$element.bind('click focus', function(e) {
    if ( !$(this).data('fired') ) foo(e);

    $(this).data('fired', true);

    setTimeout(function(self) {
        $(self).data('fired', false);
    }, 200, this);

});

FIDDLE

like image 198
adeneo Avatar answered Oct 13 '22 19:10

adeneo


One more version of debounce function implementation:

link: function($scope, $element, $attrs) {

    var callOnce = (function() {
        var timeout;
        return function(e, callback) {
            clearTimeout(timeout);
            timeout = setTimeout(function() {
                callback.call(self, e);
            }.bind(this), 200); 
        };
    })();

    $element.bind('click focus mouseover', function(e) {
        callOnce.call(this, e, foo);
    });
}

Demo: http://plnkr.co/edit/HjwedaqUcGj6KncpDtwJ?p=preview

like image 31
dfsq Avatar answered Oct 13 '22 21:10

dfsq