Reputation: 4777
I have a button called 'create project', when user click the button, I want 2 things to happen:
I have the following code:
$('.create_project').click(function(e) {
e.stopDefault();
$.getJSON('/check_user_limit', function(data){
if(data.allow_to_create_project){
//trigger the click here
}else{
//modal here
}
}
});
Using 'trigger' in the above code won't work since it become a infinite loop. The unbind works the first time, but won't work the second time since the foo no longer binds to the function.
Upvotes: 0
Views: 2108
Reputation: 1353
It's pretty simple, you just do the following:
$('.foo').click(function(e) {
$(this).href = "/bar"; # done something else before the click
return true;
});
If you want to intercept the click event and not propagate it then simply return false instead. I noticed you made your example more explicit, but the solution is still somewhat similar. Instead of returning true to propagate the event, we manually trigger the click while telling the click function to swallow the event by returning false. The code would then look something like this:
$('.create_project').click(function(e) {
$.getJSON('/check_user_limit', function(data) {
if (data.allow_to_create_project) {
e.click();
} else {
//modal here
}
}
return false;
});
However, making an AJAX request to verify whether a feature is usable is usually not a good idea. If the server already knows that the user cannot create a project, then why is the button clickable in the first place? Update the control with the appropriate state instead.
Upvotes: 1
Reputation: 5693
Why bother with client-side code for this?
From a usability standpoint it would be better to check user permissions with server-side code, and, if there's a problem, have a message next to the disabled button by the time the page loads. This message would also mention what can be done in order to enable project creation for this user.
Sometimes you just have to evaluate if a particular tool is even necessary for achieving an objective.
Upvotes: 0
Reputation: 105868
I'm sort of confused. You mention unbinding yet there is no actual unbinding of events in the actual code.
If you're just trying to execute some code pre-click of an element, you're going about it the wrong way.
$('.foo').click(function(e)
{
$(this).href = "/bar";
return true; // this is implicit, but you could return false to cancel the event
});
If you're trying to do something else, then I would advocate using two separate events, with one of them being a custom event name.
Upvotes: 0
Reputation: 8784
I'm not sure why you wouldn't want to just do:
$('.foo').click(function(e) {
$(this).href = "/bar";
});
Upvotes: 0