views:

41

answers:

3

Probably I missed something, but lets say I have this:

$('a.delete').click(function(){
   resp=window.confirm("Are you sure you want to delete this?");
   if(resp)
       return true;
   else
       return false;
}

Now, I want to save that callback function into a separate js file, because I will use it in several pages. My logic told me to do this:

$('a.del').click(delete_element());

Having my js file like this:

function delete_element(){
   resp=window.confirm("Are you sure you want to delete this?");
   if(resp)
       return true;
   else
       return false;
}

This doesn't work. Everytime my page loads, it displays the confirm window, even if I haven't clicked the link.

It is clear that my logic failed this time. What am I missing?

+1  A: 

try;

$('a.delete').click(function(){
  delete_element()
}

edit

I'd be passing the reference to the element to remove to the delete_element function and removing it from there as the name of the function says delete_element not ask_to_delete_element.

griegs
+1, Wrap the function inside an anonymous function, because its not wrapped within a function the JavaScript engine is probably parsing the function during the time it does not exists, by wrapping it in a function the engine will only parse the function at the time of the click. witch would obv be when your page is fully loaded
RobertPitt
It works, however, it wont pass the result to the parent function. I will probably have to grab the result of delete_element() and return true or false to the parent accordingly.
Danny Herran
switching htat to "return delete_element()" would fix the true/false thing.
halkeye
@halkeye you are right. That solution works as well.
Danny Herran
+2  A: 

$('a.del').click(delete_element());

That is calling the function delete_element() and hoping for a function to be returned.

$('a.del').click(delete_element);

That (note the missing ()) will set the click handler to delete_element.

halkeye
Perfect. Easier than I thought. Thanks a lot.
Danny Herran
A: 

How about

function deleteElement() {
   return window.confirm("Are you sure you want to delete this?");
}

$('a.delete').click(deleteElement);

Or if this is standard behavior for your pages:

$('a.delete').live('click', function() {
   return window.confirm("Are you sure you want to delete this?");
});
ndp