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
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
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);
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With