Reputation: 869
I was trying to implement a permission check on my application as follows. If the user clicked on an element with a specific attribute check-permission
, execute a jquery function and check for permission.
The real issue i am facing is there may be more than 20 clickable elements in my application where permission check is enabled. These elements can be div
or a
tag etc and are attached to some other jquery events; for example; trigger a popup modal, redirect to a page etc.
I want to execute my permissionCheck
function before all other click events get executed. I created a custom event and bind this to the click function; but this is not working.
Can someone suggest me a good method to implement this ? Thanks in adavnce.
Upvotes: 2
Views: 598
Reputation: 34189
There are several ways to do this - stopImmediatePropagation
; getting all events using jQuery._data(this, 'events')
and wrapping it with your validation function; unbinding events and binding them back.
However, in my opinion, the most convenient and proper way is to create custom events like permitted
and unpermitted
, and attach to it instead of click
. In that way, you will be able to have both permission-aware and simple handlers. Also, the code will become more readable, because you will see which methods require permission.
$("selector")
.on('permitted', function() {
// executed if permission check passed
})
.on('unpermitted', function() {
// executed if permission check failed
})
.on('click', function() {
// executed always!
});
You can dispatch these events in your click
handler,
$(document).on('click', '[check-permission]', function(e) {
var checkResult;
// custom permission validation logic
this.dispatchEvent(new CustomEvent(checkResult ? 'permitted' : 'unpermitted'));
e.preventDefault();
});
Attach all actions which require these permissions to permitted
and it will work.
Here is the working JSFiddle demo. In this example, decrease
and increase
buttons change the size of these links if permit
checkbox is checked. Otherwise, it shows an error.
However, implementing a permission validation at client-side should only be used in decorative purposes. You shouldn't rely on this. A proper, secure and non-compromisable authorization should be implemented at the server-side.
Upvotes: 1
Reputation: 282
your answer is stopImmediatePropagation which stops bubbling like stopPropagation and prevents all other handlers execute.
Here is an example.
<div id="testFalse" data-check-permission="false">Test False</div>
<div id="testTrue" data-check-permission="true">Test True</div>
$('[data-check-permission="true"],[data-check-permission="false"]').on('click', function (event) {
var $eventTarget = $(event.currentTarget);
if ($eventTarget.data("check-permission") == false) {
event.stopImmediatePropagation();
}
});
$("#testFalse,#testTrue").on("click", function (event) {
console.log("test");
});
Upvotes: 0